-
# app/constraints/api_constraint.rb
-
1
class APIConstraint
-
1
attr_reader :version
-
-
1
DEFAULT_API_VERSION = 1
-
-
1
def initialize(options)
-
1
@version = options.fetch(:version)
-
end
-
-
1
def matches?(request)
-
set_default_api_version(request) unless api_version_specified?(request)
-
request.headers.fetch(:accept,'').include?("version=#{version}")
-
end
-
-
1
private
-
-
1
def set_default_api_version(request)
-
request.headers[:accept] = request.headers.fetch(:accept,'')
-
.concat(";version=#{DEFAULT_API_VERSION}")
-
end
-
-
1
def api_version_specified?(request)
-
request.headers.fetch(:accept,'').include?('version')
-
end
-
end
-
class ActivationsController < ApplicationController
-
before_filter :require_no_user, :only => [:new, :create]
-
rescue_from Exception, :with => :not_found
-
-
def new
-
@user = User.find_using_perishable_token(params[:activation_code], 1.week) || (raise Exception)
-
@invite_params = params[:invite]
-
flash[:notice] = "Your account has already been activated." if @user.active?
-
end
-
-
def create
-
@user = User.find(params[:id])
-
raise Exception if @user.active?
-
if @user.activate!(params)
-
# Check Code Signing Certificate Order for assign as assignee.
-
CertificateOrder.unscoped.search_validated_not_assigned(@user.email).each do |cert_order|
-
cert_order.update_attribute(:assignee, @user)
-
LockedRecipient.create_for_co(cert_order)
-
end
-
-
@user.deliver_activation_confirmation!
-
if params[:tos] # Subscriber Agreement checked
-
@user.ssl_account.update_column(:epki_agreement, DateTime.now)
-
end
-
flash[:notice] = "Your account has been activated."
-
redirect_to account_path((@user.ssl_account ? @user.ssl_account.to_slug : {}))
-
else
-
@invite_params = params[:invite]
-
render action: :new
-
end
-
end
-
end
-
class AffiliatesController < ApplicationController
-
before_filter :require_user, :except=>[:index, :details, :refer]
-
before_filter :find_affiliate, only: [:show, :sales, :links]
-
filter_access_to :update, attribute_check: true
-
filter_access_to :show, :sales, :links, attribute_check: true, require: :read
-
-
def new
-
@affiliate = Affiliate.new
-
end
-
-
def create
-
@affiliate = Affiliate.new(params[:affiliate])
-
@affiliate.ssl_account = current_user.ssl_account
-
if @affiliate.save
-
flash[:notice]="Congrats! You can start earning commissions immediately as an ssl.com affiliate."
-
redirect_to affiliate_url(@affiliate)
-
else
-
render action: "new"
-
end
-
end
-
-
def update
-
@reseller = current_user.ssl_account.reseller
-
unless params["prev.x".intern].nil?
-
go_backward
-
else
-
go_forward
-
end
-
end
-
-
def show
-
end
-
-
def sales
-
end
-
-
def refer
-
id = params[:id]
-
if Affiliate.exists?(id)
-
set_cookie(:aid,id)
-
set_cookie(:ref,request.url)
-
end
-
if id=="21"
-
redirect_to "https://#{Settings.portal_domain}/affiliate/program.php?id=101&url=#{request.url.gsub(/\/code\/\w+\/?\z/,"")}"
-
elsif id=="35"
-
redirect_to "https://#{Settings.portal_domain}/affiliate/program.php?id=102&url=#{request.url.gsub(/\/code\/\w+\/?\z/,"")}"
-
else
-
redirect_to request.url.gsub(/\/code\/\w+\/?\z/,"")
-
end
-
end
-
-
-
# belongs_to :user
-
# before_filter :login_required, :except => [:show, :about, :refer]
-
# before_filter :allowed_to_create?, :only=>[:new, :create]
-
# before_filter :protect_affiliate, :only => [:edit_profile, :edit,
-
# :update_profile, :update, :destroy, :dashboard, :link_codes]
-
#
-
# create.before do
-
# object.user_id = current_user.id
-
# end
-
#
-
# create.after do
-
# current_user.register_for_affiliate!
-
# end
-
#
-
# create.wants.html{redirect_to dashboard_affiliate_path(object)}
-
#
-
# def refer
-
# id = params[:id]
-
# cookies[ShoppingCart::AID] = {:value=>id, :path => "/", :expires => Settings.
-
# cart_cookie_days.to_i.days.from_now} if Affiliate.exists?(id)
-
# redirect_to request.url.gsub(/\/code\/\w+\/?\z/,"")
-
# end
-
#
-
# def update_profile
-
# @avatar = AffiliatePhoto.new(params[:avatar])
-
# @avatar.affiliate = @affiliate
-
# if @avatar.save
-
# @affiliate.avatar = @avatar
-
# end
-
# respond_to do |format|
-
# if @affiliate.update_attributes(params[:affiliate])
-
# format.html { redirect_to affiliate_path(@affiliate) }
-
# else
-
# format.html { render :action => "edit_profile" }
-
# end
-
# end
-
# end
-
#
-
# protected
-
#
-
# def allowed_to_create?
-
# ([:pending].include?(current_user.current_state) or !current_user.affiliates.empty?)? access_denied : true
-
# end
-
#
-
# def parent_object
-
# object.user
-
# end
-
#
-
private
-
-
def find_affiliate
-
@affiliate = Affiliate.find(params[:id])
-
end
-
#
-
# def protect_affiliate
-
# @affiliate = Affiliate.find(params[:id])
-
# unless current_user.affiliates.first == @affiliate
-
# access_denied
-
# end
-
# end
-
#
-
#
-
end
-
class Api::V1::ApiCertificateRequestsController < Api::V1::APIController
-
prepend_view_path "app/views/api/v1/api_certificate_requests"
-
include ActionController::Helpers
-
helper SiteSealsHelper
-
before_filter :set_database, if: "request.host=~/^sandbox/ || request.host=~/^sws-test/ || request.host=~/ssl.local$/"
-
before_filter :set_test, :record_parameters, except: [:scan, :analyze, :download_v1_4]
-
after_filter :notify_saved_result, except: [:create_v1_4, :download_v1_4]
-
-
# parameters listed here made available as attributes in @result
-
wrap_parameters ApiCertificateRequest, include: [*(
-
ApiCertificateRequest::ACCESSORS+
-
ApiCertificateRequest::CREATE_ACCESSORS_1_4+
-
ApiCertificateRequest::RETRIEVE_ACCESSORS+
-
ApiCertificateRequest::DETAILED_ACCESSORS+
-
ApiCertificateRequest::REPROCESS_ACCESSORS+
-
ApiCertificateRequest::REVOKE_ACCESSORS+
-
ApiCertificateRequest::DCV_EMAILS_ACCESSORS+
-
ApiCertificateRequest::CERTIFICATE_ENROLLMENT_ACCESSORS
-
).uniq]
-
-
ORDERS_DOMAIN = "https://#{Settings.community_domain}"
-
SANDBOX_DOMAIN = "https://sandbox.ssl.com"
-
SCAN_COMMAND=->(parameters, url){%x"echo QUIT | cipherscan/cipherscan #{parameters} #{url}"}
-
ANALYZE_COMMAND=->(parameters, url){%x"echo QUIT | cipherscan/analyze.py #{parameters} #{url}"}
-
-
def notify_saved_result
-
@rendered=render_to_string(template: @template)
-
unless @rendered.is_a?(String) && @rendered.include?('errors')
-
# commenting this out, it's causing encoding issues and can grow out of control
-
# @result.update_attribute :response, @rendered
-
OrderNotifier.api_executed(@rendered, request.host_with_port).deliver if @rendered and !Settings.send_api_calls.blank?
-
end
-
end
-
-
# set which parameters will be displayed via the api response
-
def set_result_parameters(result, acr)
-
ssl_slug = acr.ssl_account.to_slug
-
result.ref = acr.ref
-
result.order_status ||= acr.status # using ||= because status might have been set from CAA problems
-
result.order_amount = acr.order.amount.format
-
domain = api_result_domain(acr)
-
result.external_order_number = acr.ext_customer_ref
-
result.certificate_url = domain+certificate_order_path(ssl_slug, acr)
-
result.receipt_url = domain+order_path(ssl_slug, acr.order)
-
result.smart_seal_url = domain+certificate_order_site_seal_path(ssl_slug, acr.ref)
-
result.validation_url = domain+certificate_order_validation_path(ssl_slug, acr)
-
result.registrant = acr.certificate_content.registrant.to_api_query if
-
(acr.certificate_content && acr.certificate_content.registrant)
-
result.certificates = acr.certificate_content.x509_certificates.map(&:to_s).join("\n") if acr.certificate_content.x509_certificates
-
end
-
-
def create_v1_4
-
set_template 'create_v1_4'
-
if @result.csr_obj && !@result.csr_obj.valid?
-
@result = @result.csr_obj
-
else
-
if @result.valid? && @result.save
-
if @acr = @result.create_certificate_order
-
# successfully charged
-
if @acr.is_a?(CertificateOrder) && @acr.errors.empty?
-
if @acr.certificate_content.csr && @result.debug
-
ccr = @acr.certificate_content.csr.ca_certificate_requests.last
-
@result.api_request=ccr.parameters
-
@result.api_response=ccr.response
-
end
-
set_result_parameters(@result, @acr)
-
else
-
@result = @acr
-
end
-
end
-
else
-
InvalidApiCertificateRequest.create parameters: params, ca: "ssl.com"
-
end
-
end
-
render_200_status_noschema
-
rescue => e
-
render_500_error e
-
end
-
-
def retrieve_signed_certificates
-
set_template "retreive_signed_certificates"
-
-
if @result.valid? && @result.save
-
@result.signed_certificates = []
-
@acr = @result.find_signed_certificates_by_public_key
-
-
@acr.each do |sc|
-
@result.signed_certificates << sc.as_json['signed_certificate']
-
end
-
else
-
InvalidApiCertificateRequest.create parameters: params, ca: "ssl.com"
-
end
-
-
render_200_status
-
rescue => e
-
render_500_error e
-
end
-
-
def revoke_v1_4
-
set_template 'revoke_v1_4'
-
if @result.valid? && @result.save
-
co = @result.find_certificate_order
-
@acr = @result.find_signed_certificates(co)
-
if @acr.is_a?(Array) && @result.errors.empty?
-
if @result.serials.blank? #revoke the entire order
-
co.revoke!(@result.reason,@result.api_credential)
-
else #revoke specific certs
-
@acr.each do |signed_certificate|
-
SystemAudit.create(
-
owner: @result.api_credential,
-
target: signed_certificate,
-
notes: "api revocation from ip address #{request.remote_ip}",
-
action: "revoked"
-
)
-
signed_certificate.revoke! @result.reason
-
end
-
-
end
-
@result.status = "revoked"
-
end
-
else
-
InvalidApiCertificateRequest.create parameters: params, ca: "ssl.com"
-
end
-
render_200_status
-
rescue => e
-
render_500_error e
-
end
-
-
def generate_certificate_v1_4
-
set_template "generate_certificate_v1_4"
-
-
if @result.valid? && @result.save
-
co = @result.find_certificate_order
-
# if co.ov_validated?
-
-
options={csr: params[:csr]}
-
unless co.certificate_content.csr.blank?
-
cc_params = co.certificate_content.attributes.except(*%w{id created_at updated_at label ref})
-
new_cc = CertificateContent.new(cc_params)
-
new_cc.save if new_cc.valid?
-
new_cc.validate! if new_cc.pending_issuance?
-
-
new_cc.create_registrant(
-
co.certificate_content.registrant.attributes.except(*CertificateOrder::ID_AND_TIMESTAMP)
-
) if co.certificate_content.registrant
-
new_cc.create_locked_registrant(
-
co.certificate_content.locked_registrant.attributes.except(*CertificateOrder::ID_AND_TIMESTAMP)
-
) if co.certificate_content.locked_registrant
-
-
options[:certificate_content] = new_cc
-
end
-
-
generated_certificate = SslcomCaApi.apply_for_certificate(co, options)
-
unless generated_certificate.nil?
-
if res = generated_certificate.x509_certificates
-
co_token = co.certificate_order_tokens.where(token: params[:token], status: nil, is_expired: false).last
-
co_token.update_attribute(:is_expired, true) if co_token
-
co.update_attribute(:request_status, '')
-
-
cert_chain = ""
-
res.each do |cert|
-
cert_chain += cert.to_s
-
end
-
-
@result.cert_results = cert_chain
-
@result.cert_common_name = (res.first.subject.common_name.force_encoding('UTF-8') || res.first.serial.to_s).
-
gsub(/[\s\.\*\(\)]/,"_").downcase + '.crt'
-
end
-
end
-
else
-
InvalidApiCertificateRequest.create parameters: params, ca: "ssl.com"
-
end
-
-
render_200_status
-
rescue => e
-
render_500_error e
-
end
-
-
def certificate_enrollment_order
-
set_template "certificate_enrollment_order"
-
-
if @result.valid? && @result.save
-
if @result.certificate_enrollment
-
@result.is_ordered = true
-
else
-
@result.is_ordered = false
-
end
-
else
-
InvalidApiCertificateRequest.create parameters: params, ca: "ssl.com"
-
end
-
-
render_200_status
-
rescue => e
-
render_500_error e
-
end
-
-
def replace_v1_4
-
set_template "replace_v1_4"
-
-
if @result.csr_obj && !result.csr_obj.valid?
-
@result = @result.csr_obj
-
else
-
# ext_order_number = CertificateOrder.find_by_ref(params[:ref]).external_order_number || 'eon'
-
if @result.save
-
if @acr = @result.replace_certificate_order
-
@csr = @acr.csr
-
-
if @acr.is_a?(CertificateOrder) && @acr.errors.empty?
-
if @acr.certificate_content.csr && @result.debug=="true"
-
ccr = @acr.certificate_content.csr.ca_certificate_requests.last
-
@result.api_request=ccr.parameters
-
@result.api_response=ccr.response
-
end# @result.error_code=ccr.response_error_code
-
# @result.error_message=ccr.response_error_message
-
# @result.eta=ccr.response_certificate_eta
-
# @result.order_status = ccr.response_certificate_status
-
-
#Send validation email unless ca_id is nil
-
unless @acr.certificate_content.ca_id.nil?
-
cnames = @acr.certificate_content.certificate_names.includes(:domain_control_validations)
-
email_for_identifier = ''
-
identifier = ''
-
email_list = []
-
identifier_list = []
-
domain_ary = []
-
domain_list = []
-
emailed_domains = []
-
-
cnames.each do |cn|
-
dcv = cn.domain_control_validations.last
-
-
unless dcv.identifier_found
-
if dcv.dcv_method == 'email'
-
if DomainControlValidation.approved_email_address? CertificateName.candidate_email_addresses(
-
cn.non_wildcard_name), dcv.email_address
-
if dcv.email_address != email_for_identifier
-
if domain_list.length > 0
-
domain_ary << domain_list
-
email_list << email_for_identifier
-
identifier_list << identifier
-
domain_list = []
-
end
-
-
identifier = (SecureRandom.hex(8)+Time.now.to_i.to_s(32))[0..19]
-
email_for_identifier = dcv.email_address
-
end
-
-
domain_list << cn.name
-
emailed_domains << cn.name
-
dcv.update_attribute(:identifier, identifier)
-
end
-
else
-
if cn.dcv_verify(dcv.dcv_method)
-
dcv.satisfy! unless dcv.satisfied?
-
end
-
end
-
end
-
end
-
-
unless identifier == ''
-
ssl_slug = @result.api_credential.ssl_account.ssl_slug || @result.api_credential.ssl_account.acct_number
-
-
domain_ary << domain_list
-
email_list << email_for_identifier
-
identifier_list << identifier
-
-
email_list.each_with_index do |value, key|
-
OrderNotifier.dcv_email_send(@acr, value, identifier_list[key], domain_ary[key], nil, ssl_slug).deliver
-
end
-
end
-
end
-
-
set_result_parameters(@result, @acr)
-
@result.debug=(@result.parameters_to_hash["debug"]=="true") # && @acr.admin_submitted = true
-
else
-
@result = @acr #so that rabl can report errors
-
end
-
-
# unless @result.cert_names.blank?
-
# @result.cert_names.keys.each do |key|
-
# # expire_fragment(params[:ref] + ':' + key)
-
# Rails.cache.delete(params[:ref] + ':' + ext_order_number + ':' + key)
-
#
-
# # cache = Rails.cache.read(params[:ref] + ':' + ext_order_number + ':' + key)
-
# # unless cache && JSON.parse(cache)['tr_info']['status'] == 'validated'
-
# # Rails.cache.delete(params[:ref] + ':' + ext_order_number + ':' + key)
-
# # end
-
# end
-
# end
-
-
end
-
else
-
InvalidApiCertificateRequest.create parameters: params, ca: "ssl.com"
-
end
-
end
-
render_200_status
-
rescue => e
-
render_500_error e
-
end
-
-
def update_v1_4
-
set_template "update_v1_4"
-
-
if @result.csr_obj && !@result.csr_obj.valid?
-
# we do this sloppy maneuver because the rabl template only reports errors
-
@result = @result.csr_obj
-
else
-
# ext_order_number = CertificateOrder.find_by_ref(params[:ref]).external_order_number || 'eon'
-
if @result.save #save the api request
-
if @acr = @result.update_certificate_order
-
@csr = @acr.csr
-
# successfully charged
-
if @acr.is_a?(CertificateOrder) && @acr.errors.empty?
-
@acr.unchain_comodo if @acr.signed_certificate_duration_delta > 1
-
if @acr.certificate_content.csr && @result.debug=="true"
-
ccr = @acr.certificate_content.csr.ca_certificate_requests.first
-
@result.api_request=ccr.parameters
-
@result.api_response=ccr.response
-
end# @result.error_code=ccr.response_error_code
-
# @result.error_message=ccr.response_error_message
-
# @result.eta=ccr.response_certificate_eta
-
# @result.order_status = ccr.response_certificate_status
-
-
#Send validation email unless ca_id is nil
-
unless @acr.certificate_content.ca_id.nil?
-
cnames = @acr.certificate_content.certificate_names.includes(:domain_control_validations,
-
:certificate_content)
-
email_for_identifier = ''
-
identifier = ''
-
email_list = []
-
identifier_list = []
-
domain_ary = []
-
domain_list = []
-
emailed_domains = []
-
# succeeded_domains = []
-
# failed_domains = []
-
-
cnames.each do |cn|
-
dcv = cn.domain_control_validations.last
-
if dcv && !dcv.identifier_found # TODO DRY and apply with app/controllers/validations_controller.rb:305
-
if dcv.dcv_method == 'email'
-
if DomainControlValidation.approved_email_address? CertificateName.candidate_email_addresses(
-
cn.non_wildcard_name), dcv.email_address
-
if dcv.email_address != email_for_identifier
-
if domain_list.length>0
-
domain_ary << domain_list
-
email_list << email_for_identifier
-
identifier_list << identifier
-
domain_list = []
-
end
-
identifier = (SecureRandom.hex(8)+Time.now.to_i.to_s(32))[0..19]
-
email_for_identifier = dcv.email_address
-
end
-
-
domain_list << cn.name
-
emailed_domains << cn.name
-
dcv.update_attribute(:identifier, identifier)
-
end
-
else
-
if cn.dcv_verify(dcv.dcv_method)
-
dcv.satisfy! unless dcv.satisfied?
-
end
-
end
-
end
-
end
-
-
unless identifier == ''
-
ssl_slug = @result.api_credential.ssl_account.ssl_slug || @result.api_credential.ssl_account.acct_number
-
-
domain_ary << domain_list
-
email_list << email_for_identifier
-
identifier_list << identifier
-
-
email_list.each_with_index do |value, key|
-
OrderNotifier.dcv_email_send(@acr, value, identifier_list[key], domain_ary[key], nil, ssl_slug).deliver
-
end
-
else
-
@acr.apply_for_certificate
-
end
-
end
-
-
set_result_parameters(@result, @acr)
-
@result.debug=(@result.parameters_to_hash["debug"]=="true") # && @acr.admin_submitted = true
-
else
-
@result = @acr #so that rabl can report errors
-
end
-
-
# unless @result.cert_names.blank?
-
# @result.cert_names.keys.each do |key|
-
# # expire_fragment(params[:ref] + ':' + key)
-
# Rails.cache.delete(params[:ref] + ':' + ext_order_number + ':' + key)
-
#
-
# # cache = Rails.cache.read(params[:ref] + ':' + ext_order_number + ':' + key)
-
# # unless cache && JSON.parse(cache)['tr_info']['status'] == 'validated'
-
# # Rails.cache.delete(params[:ref] + ':' + ext_order_number + ':' + key)
-
# # end
-
# end
-
# end
-
-
end
-
-
# @result.cert_names.keys.each do |key|
-
# # expire_fragment(params[:ref] + ':' + key)
-
# cache = Rails.cache.read(params[:ref] + ':' + key)
-
# unless cache && JSON.parse(cache)['tr_info']['status'] == 'validated'
-
# Rails.cache.delete(params[:ref] + ':' + key)
-
# end
-
# end unless @result.cert_names.blank?
-
else
-
InvalidApiCertificateRequest.create parameters: params, ca: "ssl.com"
-
end
-
end
-
render_200_status
-
rescue => e
-
render_500_error e
-
end
-
-
def callback_v1_4
-
set_template "callback_v1_4"
-
-
if @result.save
-
@acr = @result.find_certificate_order
-
if @acr.is_a?(CertificateOrder) && @acr.errors.empty?
-
cert = ApiCertificateRetrieve.new(query_type: "all_certificates")
-
@acr.to_api_retrieve cert, format: "nginx"
-
co_json = Rabl::Renderer.json(cert,File.join("api","v1","api_certificate_requests", "show_v1_4"),
-
view_path: 'app/views', locals: {result:cert})
-
# co_json = render_to_string(:template => File.join("api","v1","api_certificate_requests", "show_v1_4"))
-
req,res = @acr.certificate_content.callback(co_json,@result.callback)
-
@result.callback_hook=res.body
-
@result.response=res
-
else
-
@result = @acr unless @acr.blank? # if @acr is blank then order not found
-
end
-
-
else
-
InvalidApiCertificateRequest.create parameters: params, ca: "ssl.com"
-
end
-
render_200_status
-
rescue => e
-
render_500_error e
-
end
-
-
def contacts_v1_4
-
@template = "api_certificate_requests/contacts_v1_4"
-
-
if @result.save
-
if @acr = @result.update_certificate_content_contacts
-
@result.success_message = 'Contacts were successfully updated.'
-
end
-
else
-
InvalidApiCertificateRequest.create parameters: params, ca: "ssl.com"
-
end
-
render_200_status
-
rescue => e
-
render_500_error e
-
end
-
-
def dcv_validate_v1_4
-
set_template "success_retrieve_v1_3"
-
if @result.save
-
if @certificate_order.is_a?(CertificateOrder)
-
@certificate_order.api_validate(@result)
-
@result.order_status = @certificate_order.status
-
@result.update_attribute :response, render_to_string(:template => @template)
-
render(:template => @template) and return
-
else
-
InvalidApiCertificateRequest.create parameters: params, ca: "ssl.com"
-
end
-
end
-
render action: :create_v1_3
-
end
-
-
def detail_v1_4
-
set_template "detail_v1_4"
-
-
if @result.save
-
@acr = @result.find_certificate_order
-
-
if @acr.is_a?(CertificateOrder) && @acr.errors.empty?
-
@result.menu = {}
-
-
# @result.menu[:certificate_details_tab] = permitted_to?(:show, @acr)
-
# @result.menu[:validation_status_tab] = permitted_to?(:show, @acr.validation)
-
# @result.menu[:smart_seal_tab] = permitted_to?(:show, @acr.site_seal)
-
# @result.menu[:transaction_receipt_tab] = permitted_to?(:show, @acr.order)
-
-
@result.menu[:certificate_details_tab] = true
-
@result.menu[:validation_status_tab] = true
-
@result.menu[:smart_seal_tab] = true
-
@result.menu[:transaction_receipt_tab] = true
-
-
@result.is_admin = false
-
-
@result.sub_main = {}
-
@result.sub_main[:certificate_type] = certificate_type(@acr)
-
@result.sub_main[:certificate_duration] = @acr.certificate_duration
-
@result.sub_main[:validation_level] = @acr.certificate.description["validation_level"]
-
-
if @acr.is_unused_credit? || @acr.certificate_content.csr.blank? || @acr.certificate_content.csr.signed_certificate.blank?
-
@result.sub_main[:issued_date] = 'Pending'
-
else
-
@result.sub_main[:issued_date] = @acr.certificate_content.csr.signed_certificate.created_at.strftime("%b %d, %Y")
-
end
-
-
if @acr.is_unused_credit? || @acr.certificate_content.csr.blank?
-
@result.sub_main[:requested_date] = 'N/A'
-
else
-
@result.sub_main[:requested_date] = @acr.certificate_content.csr.created_at.strftime("%b %d, %Y")
-
end
-
-
if @result.menu[:certificate_details_tab]
-
@result.cert_details = {}
-
@result.cert_details[:main] = {}
-
@result.cert_details[:main][:subject] = @acr.signed_certificate ? @acr.signed_certificate.common_name : nil
-
@result.cert_details[:main][:order_status] = @acr.status
-
@result.cert_details[:main][:order_date] = @acr.created_at
-
@result.cert_details[:main][:expiry_date] = @acr.signed_certificate ?
-
@acr.signed_certificate.expiration_date : nil
-
-
@result.cert_details[:certificate_content] = {}
-
@result.cert_details[:certificate_content][:csr_blank] = @acr.certificate_content.csr.blank?
-
@result.cert_details[:certificate_content][:fields] = {}
-
@result.cert_details[:certificate_content][:fields][:is_signed] = true
-
-
if @acr.certificate_content.csr.signed_certificate.blank?
-
csr = @acr.certificate_content.csr
-
@result.cert_details[:certificate_content][:fields][:is_signed] = false
-
@result.cert_details[:certificate_content][:fields][:organization] = csr.organization
-
@result.cert_details[:certificate_content][:fields][:organization_unit] = csr.organization_unit
-
@result.cert_details[:certificate_content][:fields][:locality] = csr.locality
-
@result.cert_details[:certificate_content][:fields][:state] = csr.state
-
@result.cert_details[:certificate_content][:fields][:country] = csr.country
-
else
-
sc = @acr.certificate_content.csr.signed_certificate
-
@result.cert_details[:certificate_content][:fields][:algorithm] = sc.signature_algorithm
-
@result.cert_details[:certificate_content][:fields][:decoded] = sc.decoded
-
end
-
-
@result.cert_details[:in_limit] = (@acr.certificate_duration(:days).to_i > @acr.max_duration) && (@acr.created_at > Date.parse('Apr 1 2015'))
-
@result.cert_details[:registrant] = @acr.certificate_content.registrant.to_api_query
-
-
if @acr.certificate_content.issued? && !@acr.certificate_content.expired?
-
csr, sc = @acr.csr, @acr.signed_certificate
-
# @result.cert_details.download = {
-
# iis7: ["Microsoft IIS (*.p7b)", certificate_file("pkcs", @acr), SignedCertificate::IIS_INSTALL_LINK],
-
# cpanel: ["WHM/cpanel", certificate_file("whm_bundle", @acr), SignedCertificate::CPANEL_INSTALL_LINK],
-
# apache: ["Apache", certificate_file("apache_bundle", @acr), SignedCertificate::APACHE_INSTALL_LINK],
-
# amazon: ["Amazon", certificate_file("amazon_bundle", @acr), SignedCertificate::AMAZON_INSTALL_LINK],
-
# nginx: ["Nginx", certificate_file("nginx", @acr), SignedCertificate::NGINX_INSTALL_LINK],
-
# v8_nodejs: ["V8+Node.js", certificate_file("nginx", @acr), SignedCertificate::V8_NODEJS_INSTALL_LINK],
-
# java: ["Java/Tomcat", certificate_file("other", @acr), SignedCertificate::JAVA_INSTALL_LINK],
-
# other: ["Other platforms", certificate_file("other", @acr), SignedCertificate::OTHER_INSTALL_LINK],
-
# bundle: ["CA bundle (intermediate certs)", certificate_file("ca_bundle", @acr), SignedCertificate::OTHER_INSTALL_LINK]
-
# }
-
@result.cert_details[:download] = [
-
["iis7", "Microsoft IIS (*.p7b)", certificate_file("pkcs", @acr), SignedCertificate::IIS_INSTALL_LINK],
-
["cpanel", "WHM/cpanel", certificate_file("whm_bundle", @acr), SignedCertificate::CPANEL_INSTALL_LINK],
-
["apache", "Apache", certificate_file("apache_bundle", @acr), SignedCertificate::APACHE_INSTALL_LINK],
-
["amazon", "Amazon", certificate_file("amazon_bundle", @acr), SignedCertificate::AMAZON_INSTALL_LINK],
-
["nginx", "Nginx", certificate_file("nginx", @acr), SignedCertificate::NGINX_INSTALL_LINK],
-
["v8_nodejs", "V8+Node.js", certificate_file("nginx", @acr), SignedCertificate::V8_NODEJS_INSTALL_LINK],
-
["java", "Java/Tomcat", certificate_file("other", @acr), SignedCertificate::JAVA_INSTALL_LINK],
-
["other", "Other platforms", certificate_file("other", @acr), SignedCertificate::OTHER_INSTALL_LINK],
-
["bundle", "CA bundle (intermediate certs)", certificate_file("ca_bundle", @acr), SignedCertificate::OTHER_INSTALL_LINK]
-
]
-
end
-
-
unless (@acr.certificate_content.csr.blank? ||
-
(!@acr.certificate_content.show_validation_view? && @acr.is_test?))
-
if @acr.certificate_content.pending_validation?
-
@result.cert_details[:domain_validation] = true
-
end
-
unless @acr.certificate.is_dv?
-
@result.cert_details[:validation_document] = {}
-
-
unless @acr.certificate_content.blank? ||
-
@acr.certificate_content.new? ||
-
@acr.certificate_content.csr_submitted? ||
-
@acr.certificate_content.info_provided? ||
-
@acr.expired?
-
@result.cert_details[:validation_document][:links] = {}
-
@result.cert_details[:validation_document][:links][:status] = true
-
-
unless @acr.validation_rules_satisfied? || @acr.certificate_content.expired?
-
@result.cert_details[:validation_document][:links][:upload] = true
-
end
-
-
unless @acr.validation.validation_histories.blank?
-
@result.cert_details[:validation_document][:links][:manage] = true
-
@result.cert_details[:validation_document][:history] = []
-
-
@acr.validation.validation_histories.each do |vh|
-
tmp = {}
-
tmp[:id] = vh.id
-
tmp[:preview] = getDocumentsPath(vh, vh.document_url(:preview)) if vh.document_content_type =~ %r(image)
-
tmp[:doc_url] = getDocumentsPath(vh, vh.document_url)
-
tmp[:file_name] = vh.document_file_name.shorten(25, false)
-
-
@result.cert_details[:validation_document][:history] << tmp
-
end
-
end
-
end
-
end
-
end
-
-
if @acr.subject
-
@result.cert_details[:visit] = @acr.subject.gsub(/^\*\./, "").downcase
-
end
-
-
unless @acr.certificate_content.blank?
-
@result.cert_details[:contacts] = {}
-
CertificateContent::CONTACT_ROLES.each do |role|
-
@result.cert_details[:contacts][role] = @acr.certificate_content.certificate_contacts.detect(&"is_#{role}?".to_sym)
-
end
-
end
-
-
@result.cert_details[:certificate_contents] = {}
-
@acr.certificate_contents.order('created_at DESC').each do |cc|
-
@result.cert_details[:certificate_contents][cc.label] = {}
-
@result.cert_details[:certificate_contents][cc.label][:server_software] = cc.server_software.try(:title)
-
@result.cert_details[:certificate_contents][cc.label][:current] = cc == @acr.certificate_content
-
-
@result.cert_details[:certificate_contents][cc.label][:csr] = {}
-
csr = cc.csr
-
@result.cert_details[:certificate_contents][cc.label][:csr][:body] = csr.body
-
@result.cert_details[:certificate_contents][cc.label][:csr][:created_at] = csr.created_at.strftime("%b %d, %Y %R %Z")
-
-
@result.cert_details[:certificate_contents][cc.label][:sc] = {}
-
sc = cc.csr.try(:signed_certificate)
-
if sc
-
@result.cert_details[:certificate_contents][cc.label][:sc][:body] = sc.body
-
@result.cert_details[:certificate_contents][cc.label][:sc][:serial] = sc.serial
-
@result.cert_details[:certificate_contents][cc.label][:sc][:created_at] = sc.created_at.strftime("%b %d, %Y %R %Z")
-
@result.cert_details[:certificate_contents][cc.label][:sc][:decoded] = sc.decoded
-
@result.cert_details[:certificate_contents][cc.label][:sc][:subject_alternative_names] = sc.subject_alternative_names
-
# @result.cert_details.certificate_contents[cc.label]['permitted_to'] = permitted_to!(:create, SignedCertificate.new)
-
end
-
end
-
-
@result.cert_details[:api_commands] = {}
-
@result.cert_details[:api_commands][:is_server] = @acr.certificate.is_server?
-
@result.cert_details[:api_commands][:comm_name] = Settings.community_name
-
@result.cert_details[:api_commands][:is_test] = @acr.is_test
-
-
@result.cert_details[:api_commands][:products] = []
-
serial_list = ['evucc256sslcom', 'ucc256sslcom', 'ov256sslcom', 'ev256sslcom', 'dv256sslcom', 'wc256sslcom', 'basic256sslcom']
-
serial_list.push('premium256sslcom') if DEPLOYMENT_CLIENT =~ Regexp.new(Settings.portal_domain)
-
serial_list.each do |serial|
-
c = Certificate.find_by_serial(serial)
-
@result.cert_details[:api_commands][:products].push('"' + c.api_product_code + '"' + ' - ' + c.title)
-
end
-
-
@result.cert_details[:api_commands][:command] = {}
-
@result.cert_details[:api_commands][:command][:command_1] = {}
-
@result.cert_details[:api_commands][:command][:command_1][:key] = @acr.csr ? 'Status/Retrieve' : 'Status'
-
@result.cert_details[:api_commands][:command][:command_1][:doc_url] =
-
'http://docs.sslcomapi.apiary.io/#get-%2Fcertificate%2F%7Bref%7D%2F%7B%3Fquery_type%2Cresponse_type%2Cresponse_encoding%7D'
-
@result.cert_details[:api_commands][:command][:command_1][:command_str] = @acr.to_api_string(action: 'show', domain_override: api_domain(@acr))
-
-
@result.cert_details[:api_commands][:command][:command_2] = {}
-
@result.cert_details[:api_commands][:command][:command_2][:key] = 'List Orders'
-
@result.cert_details[:api_commands][:command][:command_2][:doc_url] =
-
'http://docs.sslcomapi.apiary.io/#get-%2Fcertificate%2F%7Bref%7D%2F%7B%3Fquery_type%2Cresponse_type%2Cresponse_encoding%7D'
-
@result.cert_details[:api_commands][:command][:command_2][:command_str] = @acr.to_api_string(action: 'index', domain_override: api_domain(@acr))
-
-
@result.cert_details[:api_commands][:command][:command_3] = {}
-
@result.cert_details[:api_commands][:command][:command_3][:key] = 'New Order W/O CSR'
-
@result.cert_details[:api_commands][:command][:command_3][:doc_url] = 'http://docs.sslcomapi.apiary.io/#post-%2Fcertificates'
-
@result.cert_details[:api_commands][:command][:command_3][:command_str] = @acr.to_api_string(action: 'create', domain_override: api_domain(@acr))
-
-
@result.cert_details[:api_commands][:command][:command_4] = {}
-
@result.cert_details[:api_commands][:command][:command_4][:key] = 'List DCV Methods W/O CSR'
-
@result.cert_details[:api_commands][:command][:command_4][:doc_url] =
-
'http://docs.sslcomapi.apiary.io/#get-%2Fcertificate%2F%7Bref%7D%2Fvalidations%2Fmethods%7B%3Faccount_key%2Csecret_key%7D'
-
@result.cert_details[:api_commands][:command][:command_4][:command_str] =
-
@acr.to_api_string(action: 'dcv_methods_wo_csr', domain_override: api_domain(@acr))
-
-
if @acr.certificate_content.registrant
-
if @acr.csr
-
@result.cert_details[:api_commands][:command][:command_5] = {}
-
@result.cert_details[:api_commands][:command][:command_5][:key] = 'New Order W/ CSR'
-
@result.cert_details[:api_commands][:command][:command_5][:doc_url] = 'http://docs.sslcomapi.apiary.io/#post-%2Fcertificates'
-
@result.cert_details[:api_commands][:command][:command_5][:command_str] = @acr.to_api_string(action: 'create_w_csr', domain_override: api_domain(@acr))
-
-
@result.cert_details[:api_commands][:command][:command_6] = {}
-
@result.cert_details[:api_commands][:command][:command_6][:key] = 'List DCV Methods W/ CSR'
-
@result.cert_details[:api_commands][:command][:command_6][:doc_url] = 'http://docs.sslcomapi.apiary.io/#post-%2Fcertificates%2Fvalidations%2Fcsr_hash'
-
@result.cert_details[:api_commands][:command][:command_6][:command_str] = @acr.to_api_string(action: 'dcv_methods_w_csr', domain_override: api_domain(@acr))
-
-
@result.cert_details[:api_commands][:command][:command_7] = {}
-
@result.cert_details[:api_commands][:command][:command_7][:key] = 'Update DCV'
-
@result.cert_details[:api_commands][:command][:command_7][:doc_url] = 'http://docs.sslcomapi.apiary.io/#put-%2Fcertificate%2F%7Bref%7D'
-
@result.cert_details[:api_commands][:command][:command_7][:command_str] = @acr.to_api_string(action: 'update_dcv', domain_override: api_domain(@acr))
-
end
-
if @acr.external_order_number
-
@result.cert_details[:api_commands][:command][:command_8] = {}
-
@result.cert_details[:api_commands][:command][:command_8][:key] = 'Process CSR or Reissue'
-
@result.cert_details[:api_commands][:command][:command_8][:doc_url] = 'http://docs.sslcomapi.apiary.io/#put-%2Fcertificate%2F%7Bref%7D'
-
@result.cert_details[:api_commands][:command][:command_8][:command_str] = @acr.to_api_string(action: 'update', domain_override: api_domain(@acr))
-
-
@result.cert_details[:api_commands][:command][:command_9] = {}
-
@result.cert_details[:api_commands][:command][:command_9][:key] = 'Revoke'
-
@result.cert_details[:api_commands][:command][:command_9][:doc_url] =
-
'http://docs.sslcomapi.apiary.io/#reference/ssl-certificates/certificate-order/revoke-certificate'
-
@result.cert_details[:api_commands][:command][:command_9][:command_str] = @acr.to_api_string(action: 'revoke', domain_override: api_domain(@acr))
-
end
-
end
-
-
# TODO: In case of Admin.
-
end
-
-
# if @result.cert_details.menu[:validation_status_tab]
-
-
if @result.menu[:smart_seal_tab]
-
ss = @acr.site_seal
-
-
@result.smart_seal = {}
-
@result.smart_seal[:main] = {}
-
@result.smart_seal[:main][:subject] = @acr.signed_certificate ? @acr.signed_certificate.common_name : nil
-
@result.smart_seal[:main][:cert_status] = certificate_status(@acr, true)
-
@result.smart_seal[:main][:site_seal_status] = site_seal_status(ss) unless ss && ss.blank?
-
-
@result.smart_seal[:site_seal_id] = ss.id unless ss && ss.blank?
-
@result.smart_seal[:is_ev] = @acr.certificate.is_ev?
-
@result.smart_seal[:is_dv] = @acr.certificate.is_dv?
-
@result.smart_seal[:expired] = @acr.certificate_content.expired?
-
@result.smart_seal[:valid_his_blank] = @acr.validation.validation_histories.blank?
-
@result.smart_seal[:preferred_artifacts_status] = ss.preferred_artifacts_status unless ss && ss.blank?
-
@result.smart_seal[:preferred_seal_image] = ss.preferred_seal_image? unless ss && ss.blank?
-
@result.smart_seal[:workflow_state] = ss.workflow_state unless ss && ss.blank?
-
@result.smart_seal[:is_disabled] = ss.is_disabled? unless ss && ss.blank?
-
-
co = ss.latest_certificate_order #TODO: different with @ACR?
-
r = co.certificate_content.registrant
-
-
@result.smart_seal[:co_subject] = @acr.subject
-
@result.smart_seal[:secured_site_report_subject] = co.display_subject
-
@result.smart_seal[:has_artifacts] = ss.has_artifacts? unless ss && ss.blank?
-
@result.smart_seal[:ss_ref] = ss.ref unless ss && ss.blank?
-
@result.smart_seal[:report_certificate_status] = certificate_status(@acr)
-
-
if r
-
@result.smart_seal[:registrant_company_name] = r.company_name
-
@result.smart_seal[:registrant_city_state_country] = [r.city, r.state, r.country].join(', ')
-
end
-
-
@result.smart_seal[:community_name] = Settings.community_name
-
@result.smart_seal[:cc_validated] = @acr.certificate_content.validated?
-
@result.smart_seal[:cc_issued] = @acr.certificate_content.issued?
-
@result.smart_seal[:sc_dv] = @acr.csr.signed_certificate.is_dv?
-
-
# @result.smart_seal[:hide_document] =
-
# @acr.other_party_validation_request && @acr.other_party_validation_request.hide_documents?
-
@result.smart_seal[:validation_histories] = []
-
validation_histories = @acr.validation_histories
-
validation_histories.each do |validation|
-
tmp = {}
-
tmp[:id] = validation.id
-
tmp[:thumb] = getDocumentsPath(validation, validation.document_url(:thumb)) if validation.document_content_type =~ %r(image)
-
tmp[:preview] = getDocumentsPath(validation, validation.document_url(:preview)) if validation.document_content_type =~ %r(image)
-
tmp[:doc_url] = getDocumentsPath(validation, validation.document_url)
-
tmp[:file_name] = validation.document_file_name.shorten(25, false)
-
tmp[:file_size] = bytesToSize(Integer(validation.document_file_size))
-
tmp[:created_at] = validation.created_at.strftime("%b %d, %Y")
-
tmp[:updated_at] = validation.updated_at.strftime("%b %d, %Y")
-
tmp[:publish_to_site_seal] = validation.publish_to_site_seal
-
tmp[:viewing_method] = validation.preferred_viewing_method
-
tmp[:publish_to_site_seal_approval] = validation.publish_to_site_seal_approval
-
tmp[:satisfies_validation_methods] = validation.satisfies_validation_methods.join(', ') unless validation.satisfies_validation_methods.blank?
-
-
tmp[:validation_rules] = []
-
valid_rules = validation.validation_rules
-
valid_rules.each do |vr|
-
tmp[:validation_rules] << vr.description
-
end
-
-
@result.smart_seal[:validation_histories] << tmp
-
end
-
# @result.smart_seal[:validation_histories] = @acr.validation_histories
-
# TODO: Other_party_request(CO)
-
@result.smart_seal[:other_party_request] = false
-
@result.smart_seal[:valid_his_preview] = false
-
end
-
-
# if @result.menu[:transaction_receipt_tab]
-
-
render(:template => @template) and return
-
end
-
else
-
InvalidApiCertificateRequest.create parameters: params, ca: "ssl.com"
-
end
-
rescue => e
-
render_500_error e
-
end
-
-
def update_site_seal_v1_4
-
@template = "api_certificate_requests/site_seal_tab_v1_4.rabl"
-
-
if @result.save
-
@acr = @result.find_certificate_order
-
-
if params[:artifacts_status]
-
@acr.site_seal.update_attributes(params[:artifacts_status])
-
@result.artifacts_status = @acr.site_seal.preferred_artifacts_status
-
end
-
-
if params[:publish_to_site_seal]
-
validation_his = ValidationHistory.find(params[:id])
-
validation_his.update_attributes(params[:publish_to_site_seal])
-
@result.id = params[:id]
-
@result.publish_to_site_seal = validation_his.publish_to_site_seal
-
end
-
-
if params[:viewing_method]
-
validation_his = ValidationHistory.find(params[:id])
-
validation_his.update_attributes(params[:viewing_method])
-
@result.id = params[:id]
-
@result.viewing_method = validation_his.preferred_viewing_method
-
end
-
-
if params[:publish_to_site_seal_approval]
-
validation_his = ValidationHistory.find(params[:id])
-
validation_his.update_attribute(:publish_to_site_seal_approval,
-
params[:publish_to_site_seal_approval])
-
@result.id = params[:id]
-
@result.publish_to_site_seal_approval = validation_his.publish_to_site_seal_approval
-
end
-
-
else
-
InvalidApiCertificateRequest.create parameters: params, ca: "ssl.com"
-
end
-
render_200_status
-
rescue => e
-
render_500_error e
-
end
-
-
def download_v1_4
-
send_file "#{Rails.root}/tmp/certificate/#{params[:file_name]}"
-
end
-
-
def show_v1_4
-
set_template "show_v1_4"
-
if @result.valid?
-
@acr = @result.find_certificate_order
-
-
# Reading cache of Certificate order for "SSL-Certificate-Collection" API.
-
cache = Rails.cache.read('api-retrieve-ssl-cert-' + params[:ref])
-
is_new = false
-
-
if cache.blank?
-
is_new = true
-
elsif JSON.parse(cache)['private_cache_key'] != @acr.certificate_content.updated_at.strftime('%Y%m%d%H%M%S')
-
is_new = true
-
Rails.cache.delete('api-retrieve-ssl-cert-' + params[:ref])
-
end
-
-
if is_new
-
if @acr.is_a?(CertificateOrder) && @acr.errors.empty?
-
package_certificate_order(@result, @acr)
-
-
# Caching Certificate order for "Retrieve an SSL Certificate" API.
-
@result.private_cache_key = @acr.certificate_content.updated_at.strftime('%Y%m%d%H%M%S')
-
-
ActiveRecord::Base.include_root_in_json = false
-
cache_key = 'api-retrieve-ssl-cert-' + params[:ref]
-
-
Rails.cache.write(cache_key, @result.to_json(:methods => [
-
:description, :product, :product_name, :order_status, :order_date, :registrant, :certificates,
-
:common_name, :domains_qty_purchased, :wildcard_qty_purchased, :subject_alternative_names, :validations,
-
:effective_date, :expiration_date, :algorithm, :external_order_number, :domains, :site_seal_code,
-
:subscriber_agreement, :server_software, :contacts, :private_cache_key
-
]))
-
end
-
else
-
@result = ApiCertificateRetrieve.new(JSON.parse(cache))
-
end
-
else
-
InvalidApiCertificateRequest.create parameters: params, ca: "ssl.com"
-
end
-
render_200_status
-
rescue => e
-
render_500_error e
-
end
-
-
def view_upload_v1_4
-
@template = "api_certificate_requests/view_upload_v1_4"
-
-
if @result.save
-
@acr = @result.find_certificate_order
-
-
if @acr.is_a?(CertificateOrder) && @acr.errors.empty?
-
@result.ref = @acr.ref
-
@result.subject = @acr.subject
-
@result.checkout_in_progress = @acr.validation_stage_checkout_in_progress?
-
@result.other_party_request = false
-
@result.community_name = Settings.community_name
-
@result.is_dv = @acr.certificate.is_dv?
-
@result.is_dv_or_basic = @acr.certificate.is_dv_or_basic?
-
@result.is_ev = @acr.certificate.is_ev?
-
@result.all_domains = @acr.all_domains.join(', ')
-
@result.acceptable_file_types = ValidationHistory.acceptable_file_types
-
@result.validation_rules = @acr.validation.validation_rules.sort{|a,b|a.id<=>b.id}
-
-
render(:template => @template) and return
-
end
-
else
-
InvalidApiCertificateRequest.create parameters: params, ca: "ssl.com"
-
end
-
rescue => e
-
render_500_error e
-
end
-
-
def upload_v1_4
-
@template = "api_certificate_requests/upload_v1_4"
-
-
if @result.save
-
@acr = @result.find_certificate_order
-
-
if @acr.is_a?(CertificateOrder) && @acr.errors.empty?
-
count = 0
-
error = []
-
message = ""
-
@files = params[:fileUpload] || []
-
-
@files.each do |file|
-
if file.respond_to?(:original_filename) && file.original_filename.include?("zip")
-
FileUtils.mkdir_p "#{Rails.root}/tmp/zip/temp" if !File.exist?("#{Rails.root}/tmp/zip/temp")
-
-
if file.size > Settings.max_content_size.to_i.megabytes
-
break error = <<-EOS
-
Too Large: zip file #{file.original_filename} is larger than
-
#{help.number_to_human_size(Settings.max_content_size.to_i.megabytes)}
-
EOS
-
end
-
-
@zip_file_name=file.original_filename
-
File.open("#{Rails.root}/tmp/zip/#{file.original_filename}", "wb") do |f|
-
f.write(file.read)
-
end
-
-
zf = Zip::ZipFile.open("#{Rails.root}/tmp/zip/#{file.original_filename}")
-
if zf.size > Settings.max_num_releases.to_i
-
break error = <<-EOS
-
Too Many Files: zip file #{file.original_filename} contains more than
-
#{Settings.max_num_releases.to_i} files.
-
EOS
-
end
-
-
zf.each do |entry|
-
begin
-
fpath = File.join("#{Rails.root}/tmp/zip/temp/",entry.name.downcase)
-
-
if(File.exists?(fpath))
-
File.delete(fpath)
-
end
-
-
zf.extract(entry, fpath)
-
@created_releases << create_with_attachment(LocalFile.new(fpath))
-
-
count += 1
-
rescue Errno::ENOENT, Errno::EISDIR
-
error = "Invalid contents: zip entries with directories not allowed"
-
break
-
ensure
-
if (File.exists?(fpath))
-
if File.directory?(fpath)
-
FileUtils.remove_dir fpath, :force=>true
-
else
-
FileUtils.remove_file fpath, :force=>true
-
end
-
end
-
-
@created_releases.each {|release| release.destroy} unless error.blank?
-
end
-
end
-
File.delete(zf.name) if (File.exists?(zf.name))
-
@created_releases.each do |doc|
-
doc.errors.each{|attr, msg|
-
error << "#{attr} #{msg}: " }
-
end
-
else
-
vh = create_with_attachment(LocalFile.new(file.path, file.original_filename), @acr)
-
vh.errors.each{|attr, msg|
-
error << "#{attr} #{msg}: " }
-
count += 1 if vh
-
error << "Error: Document for #{file.original_filename} was not
-
created. Please notify system admin at #{Settings.support_email}" unless vh
-
end
-
end
-
-
if error.blank?
-
unless @files.blank?
-
-
files_were = (count > 1 or count == 0)? "documents were" : "document was"
-
@result.success_message = "#{i.in_words.capitalize} (#{i}) #{files_were}
-
successfully saved."
-
-
@acr.confirmation_recipients.map{|r|r.split(" ")}.flatten.uniq.each do |c|
-
OrderNotifier.validation_documents_uploaded(c, @acr, @files).deliver
-
end
-
-
OrderNotifier.validation_documents_uploaded(Settings.notify_address, @acr, @files).deliver
-
OrderNotifier.validation_documents_uploaded_comodo("evdocs@comodo.com", @acr, @files).
-
deliver if (@acr.certificate.is_ev? && @acr.ca_name=="comodo")
-
end
-
-
# checkout={}
-
# if @acr.certificate_content.contacts_provided?
-
# @message.certificate_content.pend_validation!(host: request.host_with_port) if @other_party_validation_request.blank?
-
# checkout={checkout: "true"}
-
# end
-
end
-
@result.errors = error
-
-
render(:template => @template) and return
-
end
-
else
-
InvalidApiCertificateRequest.create parameters: params, ca: "ssl.com"
-
end
-
rescue => e
-
render_500_error e
-
end
-
-
def api_parameters_v1_4
-
set_template "api_parameters_v1_4"
-
-
if @result.save
-
@acr = @result.find_certificate_order
-
-
if @acr.is_a?(CertificateOrder) && @acr.errors.empty?
-
# Reading cache of Api Parameters for "Retrieve acceptable domain validation methods for Certificate" API.
-
cache = Rails.cache.read('api-retrieve-domain-valid-methods-' + @acr.ref + '-' + @result.api_call)
-
-
if cache.blank?
-
api_domain = "https://" + (@acr.is_test ? Settings.test_api_domain : Settings.api_domain)
-
@result.parameters = @acr.to_api_string(action: @result.api_call, domain_override: api_domain, caller: "api")
-
-
# Caching Api Parameters for "Retrieve acceptable domain validation methods for Certificate" API.
-
Rails.cache.write('api-retrieve-domain-valid-methods-' + @acr.ref + '-' + @result.api_call, @result.parameters.to_json)
-
else
-
@result.parameters = JSON.parse(cache)
-
end
-
-
render(:template => @template) and return
-
end
-
else
-
InvalidApiCertificateRequest.create parameters: params, ca: "ssl.com"
-
end
-
rescue => e
-
render_500_error e
-
end
-
-
def scan
-
@result=->(parameters, url) do
-
timeout(60) do
-
SCAN_COMMAND.call parameters, url
-
end
-
end
-
respond_to do |format|
-
format.html {render inline: @result.call("--curves", params[:url])}
-
format.js {render json: @result.call("--curves -j", params[:url])}
-
format.json {render json: @result.call("--curves -j", params[:url])}
-
end
-
end
-
-
def analyze
-
@result=->(parameters, url) do
-
timeout(60) do
-
ANALYZE_COMMAND.call parameters, url
-
end
-
end
-
respond_to do |format|
-
format.html {render inline: @result.call("-t", params[:url])}
-
format.js {render json: @result.call("-j -t", params[:url])}
-
format.json {render json: @result.call("-j -t", params[:url])}
-
end
-
end
-
-
def index_v1_4
-
set_template "index_v1_4"
-
@result.end = DateTime.now if @result.end.blank?
-
client_app = params[:client_app]
-
-
if @result.save
-
@orders = @result.find_certificate_orders(params[:search],is_sandbox_or_test? ? {is_test: true} : nil)
-
-
page = params[:page] || 1
-
per_page = params[:per_page] || PER_PAGE_DEFAULT
-
@acrs = paginate @orders, per_page: per_page.to_i, page: page.to_i
-
-
if @acrs.is_a?(ActiveRecord::Relation)
-
@results = []
-
@acrs.each do |acr|
-
c = acr.certificate
-
sc = acr.signed_certificate
-
cc = acr.certificate_content
-
is_new = false
-
-
# Reading cache of Individual Certificate order for "SSL-Certificate-Collection" API.
-
cache = Rails.cache.read('api-ssl-cert-collection-' + acr.ref + '-' + (client_app ? 'T' : 'F'))
-
-
if cache.blank?
-
is_new = true
-
elsif JSON.parse(cache)['private_cache_key'] != cc.updated_at.strftime('%Y%m%d%H%M%S')
-
is_new = true
-
Rails.cache.delete('api-ssl-cert-collection-' + acr.ref)
-
end
-
-
if is_new
-
result = ApiCertificateRetrieve.new(ref: acr.ref)
-
result.order_date = acr.created_at
-
result.order_status = acr.status
-
result.domains = acr.all_domains
-
result.description = acr.description
-
result.common_name = sc ? sc.common_name : nil
-
result.product_type = c.product
-
result.period = acr.certificate_contents.first.duration
-
-
if client_app
-
result.expiration_date = sc ? sc.expiration_date : nil
-
else
-
result.registrant = cc.registrant.to_api_query if (cc && cc.registrant)
-
result.validations = result.validations_from_comodo(acr) if acr.external_order_number #'validations' kept executing twice so it was renamed to 'validations_from_comodo'
-
-
if c.is_ucc?
-
result.domains_qty_purchased = acr.purchased_domains('all').to_s
-
result.wildcard_qty_purchased = acr.purchased_domains('wildcard').to_s
-
else
-
result.domains_qty_purchased = '1'
-
result.wildcard_qty_purchased = c.is_wildcard? ? '1' : '0'
-
end
-
-
if (sc && result.query_type!='order_status_only')
-
signed_certificate_format = sc.to_format(
-
response_type: @result.response_type, #assume comodo issued cert
-
response_encoding: @result.response_encoding
-
)
-
result.certificates = signed_certificate_format || sc.to_nginx
-
result.subject_alternative_names = sc.subject_alternative_names
-
result.effective_date = sc.effective_date
-
result.expiration_date = sc.expiration_date
-
result.algorithm = sc.is_SHA2? ? 'SHA256' : 'SHA1'
-
# below is forcing nginx to return content_type: html which is breaking SSL Manager
-
# result.site_seal_code = ERB::Util.json_escape(render_to_string(
-
# partial: 'site_seals/site_seal_code.html.haml',
-
# locals: {co: acr},
-
# layout: false)
-
# )
-
end
-
end
-
-
# Caching Individual Certificate order for "SSL-Certificate-Collection" API.
-
result.private_cache_key = cc.updated_at.strftime('%Y%m%d%H%M%S')
-
-
ActiveRecord::Base.include_root_in_json = false
-
cache_key = 'api-ssl-cert-collection-' + acr.ref + '-' + (client_app ? 'T' : 'F')
-
-
Rails.cache.write(cache_key, result.to_json(:methods => [
-
:ref, :description, :order_status, :order_date, :registrant, :certificates, :common_name, :domains_qty_purchased,
-
:wildcard_qty_purchased, :subject_alternative_names, :validations, :effective_date, :expiration_date, :algorithm,
-
:domains, :site_seal_code, :product_type, :period, :private_cache_key]))
-
else
-
result = ApiCertificateRetrieve.new(JSON.parse(cache))
-
end
-
-
@results << result
-
end
-
end
-
-
if client_app
-
render json: serialize_models(@results, meta: {orders_count: @orders.count, page: page, per_page: per_page})
-
else
-
@default_fields = [
-
'ref',
-
'description',
-
'order_status',
-
'order_date',
-
'registrant',
-
'certificates',
-
'common_name',
-
'domains_qty_purchased',
-
'wildcard_qty_purchased',
-
'subject_alternative_names',
-
'validations',
-
'effective_date',
-
'expiration_date',
-
'algorithm',
-
'domains',
-
'site_seal_code',
-
'external_order_number'
-
]
-
-
@fields = []
-
if params[:fields] && !params[:fields].empty?
-
params[:fields].split(',').each do |field|
-
@fields << field
-
end
-
else
-
@fields = @default_fields
-
end
-
-
render(template: @template) and return
-
end
-
else
-
InvalidApiCertificateRequest.create parameters: params, ca: "ssl.com"
-
end
-
rescue => e
-
render_500_error e
-
end
-
-
def retrieve_v1_3
-
if @result.save && @certificate_order.is_a?(CertificateOrder)
-
set_template "success_retrieve_v1_3"
-
@result.order_status = @certificate_order.status
-
@result.update_attribute :response, render_to_string(:template => @template)
-
render(:template => @template) and return
-
else
-
InvalidApiCertificateRequest.create parameters: params, ca: "ssl.com"
-
end
-
render action: :create_v1_3
-
end
-
-
def dcv_emails_v1_3
-
set_template "dcv_emails_v1_3"
-
-
if @result.save
-
@result.email_addresses={}
-
# @certificate_order=find_certificate_order
-
# @certificate_order.is_a?(CertificateOrder)
-
-
if @result.domain
-
# Reading cache of email address for "Acceptable Email addresses for domain control validation" API.
-
cache = Rails.cache.read('api-email-addresses-' + @result.domain)
-
-
if cache.blank?
-
@result.email_addresses = ComodoApi.domain_control_email_choices(@result.domain).email_address_choices
-
-
# Caching Certificate order for "Retrieve an SSL Certificate" API.
-
cache_key = 'api-email-addresses-' + @result.domain
-
Rails.cache.write(cache_key, @result.email_addresses.join('-'))
-
else
-
@result.email_addresses = cache.split('-')
-
end
-
else
-
@result.domains.each do |domain|
-
# Reading cache of email address for "Acceptable Email addresses for domain control validation" API.
-
cache = Rails.cache.read('api-email-addresses-' + domain)
-
-
if cache.blank?
-
@result.email_addresses.merge! domain => CertificateName.candidate_email_addresses(domain)
-
-
# Caching Certificate order for "Retrieve an SSL Certificate" API.
-
cache_key = 'api-email-addresses-' + domain
-
Rails.cache.write(cache_key, @result.email_addresses[domain].join('-'))
-
else
-
@result.email_addresses.merge! domain => cache.split('-')
-
end
-
end
-
end
-
-
unless @result.email_addresses.blank?
-
render(:template => @template) and return
-
end
-
else
-
InvalidApiCertificateRequest.create parameters: params, ca: "ssl.com"
-
end
-
end
-
-
def pretest_v1_4
-
set_template "pretest_v1_4"
-
if @result.save && find_certificate_order.is_a?(CertificateOrder)
-
http_to_s = false # dcv_verify(params[:protocol])
-
@result.is_passed = http_to_s
-
-
render_200_status
-
end
-
rescue => e
-
render_500_error e
-
end
-
-
def dcv_methods_v1_4
-
set_template "dcv_methods_v1_4"
-
if @result.save #save the api request
-
@acr = @result.find_certificate_order
-
@result.dcv_methods={}
-
if @acr.all_domains
-
@result.instructions = ApiDcvMethods::INSTRUCTIONS
-
unless @acr.csr.blank?
-
@result.md5_hash = @acr.csr.md5_hash
-
@result.sha2_hash = @acr.csr.sha2_hash
-
@result.dns_md5_hash = @acr.csr.dns_md5_hash
-
@result.dns_sha2_hash = @acr.csr.dns_sha2_hash
-
@result.ca_tag = @acr.csr.ca_tag
-
end
-
@acr.all_domains.each do |domain|
-
@result.dcv_methods.merge! domain=>{}
-
@result.dcv_methods[domain].merge! "email_addresses"=> @acr.certificate_content.ca_id.nil? ?
-
ComodoApi.domain_control_email_choices(domain).email_address_choices :
-
CertificateName.candidate_email_addresses(domain)
-
unless @acr.csr.blank?
-
@result.dcv_methods[domain].merge! "http_csr_hash"=>
-
{"http"=>"#{@acr.csr.dcv_url(false,domain)}",
-
"allow_https"=>"true",
-
"contents"=>"#{@result.sha2_hash}\n#{@result.ca_tag}#{"\n#{@acr.csr.unique_value}" unless @acr.csr.unique_value.blank?}"}
-
@result.dcv_methods[domain].merge! "cname_csr_hash"=>{"cname"=>"#{@result.dns_md5_hash}.#{domain}. CNAME #{@result.dns_sha2_hash}.#{@result.ca_tag}.","name"=>"#{@result.dns_md5_hash}.#{domain}","value"=>"#{@result.dns_sha2_hash}.#{@result.ca_tag}."}
-
end
-
end
-
end
-
unless @result.dcv_methods.blank?
-
render(:template => @template) and return
-
end
-
else
-
InvalidApiCertificateRequest.create parameters: params, ca: "ssl.com"
-
end
-
rescue => e
-
render_500_error e
-
end
-
-
def dcv_methods_csr_hash_v1_4
-
set_template "dcv_methods_v1_4"
-
if @result.save #save the api request
-
@acr = CertificateOrder.new
-
@acr.certificate_contents.build.build_csr(body: @result.csr)
-
-
if @acr.csr.errors.empty?
-
@result.dcv_methods={}
-
-
if @acr.csr.common_name
-
# Reading cache of csr hashes for "Retrieve all validation methods based on hash of certificate signing request" API.
-
cache = Rails.cache.read('api-csr-hash-' + @acr.csr.md5_hash)
-
-
if cache.blank?
-
@result.instructions = ApiDcvMethods::INSTRUCTIONS
-
-
unless @acr.csr.blank?
-
@result.md5_hash = @acr.csr.md5_hash
-
@result.sha2_hash = @acr.csr.sha2_hash
-
@result.dns_md5_hash = @acr.csr.dns_md5_hash
-
@result.dns_sha2_hash = @acr.csr.dns_sha2_hash
-
@result.ca_tag = @acr.csr.ca_tag
-
end
-
-
([@acr.csr.common_name]+(@result.domains || [])).compact.map(&:downcase).uniq.each do |domain|
-
@result.dcv_methods.merge! domain=>{}
-
@result.dcv_methods[domain].merge! "email_addresses"=> @acr.certificate_content.ca_id.nil? ?
-
ComodoApi.domain_control_email_choices(domain).email_address_choices :
-
CertificateName.candidate_email_addresses(domain)
-
unless @acr.csr.blank?
-
@result.dcv_methods[domain].merge! "http_csr_hash"=>
-
{"http"=>"#{@acr.csr.dcv_url(false,domain)}",
-
"allow_https"=>"true",
-
"contents"=>"#{@result.sha2_hash}\n#{@result.ca_tag}#{"\n#{@acr.csr.unique_value}" unless @acr.csr.unique_value.blank?}"}
-
@result.dcv_methods[domain].merge! "cname_csr_hash"=>{"cname"=>"#{@result.dns_md5_hash}.#{domain}. CNAME #{@result.dns_sha2_hash}.#{@result.ca_tag}.","name"=>"#{@result.dns_md5_hash}.#{domain}","value"=>"#{@result.dns_sha2_hash}.#{@result.ca_tag}."}
-
end
-
end
-
-
# Caching CSR Hashes for "Retrieve all validation methods based on hash of certificate signing request" API.
-
ActiveRecord::Base.include_root_in_json = false
-
cache_key = 'api-csr-hash-' + @result.md5_hash
-
Rails.cache.write(cache_key, @result.to_json(:methods => [
-
:instructions, :md5_hash, :sha2_hash, :dns_md5_hash, :dns_sha2_hash, :dcv_methods, :ca_tag]))
-
else
-
@result.instructions = JSON.parse(cache)['instructions']
-
@result.md5_hash = JSON.parse(cache)['md5_hash']
-
@result.sha2_hash = JSON.parse(cache)['sha2_hash']
-
@result.dns_md5_hash = JSON.parse(cache)['dns_md5_hash']
-
@result.dns_sha2_hash = JSON.parse(cache)['dns_sha2_hash']
-
@result.dcv_methods = JSON.parse(cache)['dcv_methods']
-
@result.ca_tag = JSON.parse(cache)['ca_tag']
-
end
-
end
-
-
unless @result.dcv_methods.blank?
-
render(:template => @template) and return
-
end
-
else
-
@result=@acr.csr #so that rabl can report errors
-
end
-
else
-
InvalidApiCertificateRequest.create parameters: params, ca: "ssl.com"
-
end
-
render action: :dcv_methods_v1_4
-
rescue => e
-
render_500_error e
-
end
-
-
def dcv_email_resend_v1_3
-
if @result.save
-
@result.sent_at=Time.now
-
unless @result.email_addresses.blank?
-
set_template "success_dcv_email_resend_v1_3"
-
render(:template => @template) and return
-
end
-
else
-
InvalidApiCertificateRequest.create parameters: params, ca: "ssl.com"
-
end
-
render action: :create_v1_3
-
end
-
-
def dcv_revoke_v1_3
-
set_template "success_dcv_emails_v1_3"
-
if @result.save
-
@result.email_addresses=ComodoApi.domain_control_email_choices(@result.domain_name).email_address_choices
-
unless @result.email_addresses.blank?
-
render(:template => @template) and return
-
end
-
else
-
InvalidApiCertificateRequest.create parameters: params, ca: "ssl.com"
-
end
-
render action: :create_v1_3
-
end
-
-
private
-
def package_certificate_order(result,acr)
-
result.order_date = acr.created_at
-
result.order_status = acr.status
-
result.registrant = acr.certificate_content.registrant.to_api_query if (acr.certificate_content && acr.certificate_content.registrant)
-
result.contacts = acr.certificate_content.certificate_contacts if (acr.certificate_content && acr.certificate_content.certificate_contacts)
-
result.validations = result.validations_from_comodo(acr) if acr.external_order_number #'validations' kept executing twice so it was renamed to 'validations_from_comodo'
-
result.description = acr.description
-
result.product = acr.certificate.api_product_code
-
result.product_name = acr.certificate.product
-
result.subscriber_agreement = acr.certificate.subscriber_agreement_content if result.show_subscriber_agreement =~ /[Yy]/
-
result.external_order_number = acr.ext_customer_ref
-
result.server_software = acr.server_software.id if acr.server_software
-
-
if acr.certificate.is_ucc?
-
result.domains_qty_purchased = acr.purchased_domains('all').to_s
-
result.wildcard_qty_purchased = acr.purchased_domains('wildcard').to_s
-
else
-
result.domains_qty_purchased = "1"
-
result.wildcard_qty_purchased = acr.certificate.is_wildcard? ? "1" : "0"
-
end
-
-
if (acr.signed_certificate && result.query_type != "order_status_only")
-
result.certificates =
-
acr.signed_certificate.to_format(response_type: result.response_type, #assume comodo issued cert
-
response_encoding: result.response_encoding) || acr.signed_certificate.to_nginx
-
result.common_name = acr.signed_certificate.common_name
-
result.subject_alternative_names = acr.signed_certificate.subject_alternative_names
-
result.effective_date = acr.signed_certificate.effective_date
-
result.expiration_date = acr.signed_certificate.expiration_date
-
result.algorithm = acr.signed_certificate.is_SHA2? ? "SHA256" : "SHA1"
-
# result.site_seal_code = ERB::Util.json_escape(render_to_string(
-
# partial: 'site_seals/site_seal_code.html.haml',
-
# locals: {co: acr},
-
# layout: false
-
# ))
-
elsif (acr.csr)
-
result.certificates = nil
-
result.common_name = acr.csr.common_name
-
end
-
end
-
-
def record_parameters
-
klass = case params[:action]
-
when "create_v1_3"
-
ApiCertificateCreate
-
when "create_v1_4", "update_v1_4", "contacts_v1_4", "replace_v1_4"
-
ApiCertificateCreate_v1_4
-
when /revoke/
-
ApiCertificateRevoke
-
when "retrieve_v1_3", "show_v1_4", "index_v1_4", "detail_v1_4", "view_upload_v1_4", "upload_v1_4",
-
"update_site_seal_v1_4", "generate_certificate_v1_4","callback_v1_4"
-
ApiCertificateRetrieve
-
when "certificate_enrollment_order"
-
ApiCertificateEnrollment
-
when "retrieve_signed_certificates"
-
ApiSignedCertificateRequest
-
when "api_parameters_v1_4"
-
ApiParameters
-
when "quote"
-
ApiCertificateQuote
-
when "dcv_email_resend_v1_3"
-
ApiDcvEmailResend
-
when "dcv_emails_v1_3", "dcv_revoke_v1_3"
-
ApiDcvEmails
-
when "dcv_methods_v1_4", "dcv_revoke_v1_3", "dcv_methods_csr_hash_v1_4", "pretest_v1_4"
-
ApiDcvMethods
-
end
-
@result=klass.new(_wrap_parameters(params)['api_certificate_request'] || params[:api_certificate_request])
-
@result.debug ||= params[:debug] if params[:debug]
-
@result.send_to_ca ||= params[:send_to_ca] if params[:send_to_ca]
-
@result.action ||= params[:action]
-
@result.ref ||= params[:ref] if params[:ref]
-
@result.options ||= params[:options] if params[:options]
-
@result.test = @test
-
@result.request_url = request.url
-
@result.parameters = params.to_utf8.to_json
-
@result.raw_request = request.raw_post.force_encoding("ISO-8859-1").encode("UTF-8")
-
@result.request_method = request.request_method
-
@result.saved_registrant ||= params[:saved_registrant] if params[:saved_registrant]
-
end
-
-
def find_certificate_order
-
@certificate_order=@result.find_certificate_order
-
end
-
-
def csr
-
@csr || @certificate_order.csr
-
end
-
-
def api_result_domain(certificate_order=nil)
-
unless certificate_order.blank?
-
if Rails.env=~/production/i
-
"https://" + (certificate_order.is_test ? Settings.sandbox_domain : Settings.portal_domain)
-
else
-
"https://" + (certificate_order.is_test ? Settings.dev_sandbox_domain : Settings.dev_portal_domain) +":3000"
-
end
-
else
-
if is_sandbox?
-
Rails.env=~/production/i ? "https://#{Settings.sandbox_domain}" : "https://#{Settings.dev_sandbox_domain}:3000"
-
else
-
Rails.env=~/production/i ? "https://#{Settings.portal_domain}" : "https://#{Settings.dev_portal_domain}:3000"
-
end
-
end
-
end
-
-
def certificate_type(certificate_order=nil)
-
if certificate_order.is_a?(CertificateOrder)
-
unless Order.unscoped{certificate_order.order}.preferred_migrated_from_v2
-
certificate_order.certificate.description["certificate_type"]
-
else
-
certificate_order.preferred_v2_product.description.gsub /[Cc]ertificate\z/, ''
-
end
-
end
-
end
-
-
def certificate_file(type, certificate_order)
-
path = "#{Rails.root}/tmp/certificate/"
-
unless File.directory?(path)
-
FileUtils.mkdir_p(path)
-
end
-
-
if type === 'pkcs'
-
data = certificate_order.signed_certificate.to_pkcs7
-
path += certificate_order.signed_certificate.nonidn_friendly_common_name + '.p7b'
-
out_file = File.open(path, 'w')
-
out_file.puts(data)
-
out_file.close
-
elsif type === 'nginx'
-
data = certificate_order.signed_certificate.to_nginx
-
path += certificate_order.signed_certificate.nonidn_friendly_common_name + '.crt'
-
out_file = File.new(path, 'w')
-
out_file.puts(data)
-
out_file.close
-
elsif type === 'ca_bundle'
-
file = certificate_order.signed_certificate.ca_bundle
-
path += certificate_order.signed_certificate.nonidn_friendly_common_name + '.ca-bundle'
-
FileUtils.mv(file, path)
-
elsif type === 'whm_bundle'
-
file = certificate_order.signed_certificate.zipped_whm_bundle
-
path += certificate_order.signed_certificate.nonidn_friendly_common_name + '.zip'
-
FileUtils.mv(file, path)
-
elsif type === 'apache_bundle'
-
file = certificate_order.signed_certificate.zipped_apache_bundle
-
path += certificate_order.signed_certificate.nonidn_friendly_common_name + '.zip'
-
FileUtils.mv(file, path)
-
elsif type === 'amazon_bundle'
-
file = certificate_order.signed_certificate.zipped_amazon_bundle
-
path += certificate_order.signed_certificate.nonidn_friendly_common_name + '.zip'
-
FileUtils.mv(file, path)
-
elsif type === 'other'
-
file = certificate_order.certificate_content.csr.signed_certificate.
-
create_signed_cert_zip_bundle({components: true, is_windows: false})
-
path += certificate_order.friendly_common_name + '.zip'
-
FileUtils.mv(file, path)
-
end
-
-
path[(path.rindex('/') + 1)..path.length]
-
end
-
-
def create_with_attachment(file, certificate_order)
-
@val_history = ValidationHistory.new(:document => file)
-
certificate_order.validation.validation_histories << @val_history
-
@val_history.save
-
@val_history
-
end
-
-
def certificate_status(co, is_managing=nil)
-
pending = is_managing ? "info" : "warning"
-
cc=co.certificate_content
-
case cc.workflow_state
-
when "issued"
-
if cc.csr.signed_certificate.blank?
-
["certificate missing", "danger"]
-
else
-
ef, ex = [cc.csr.signed_certificate.effective_date, cc.csr.
-
signed_certificate.expiration_date]
-
if ex.blank? || ef.blank?
-
#these were signed certs transferred over and somehow were missing these dates
-
["invalid certificate", "danger"]
-
elsif ex < Time.now
-
["invalid (expired on #{ex.strftime("%b %d, %Y")})", pending]
-
elsif ef > Time.now
-
["invalid (starts on #{ef.strftime("%b %d, %Y")})", pending]
-
else
-
["valid (#{ef.strftime("%b %d, %Y")} - #{ex.strftime("%b %d, %Y")})",
-
"success"]
-
end
-
end
-
when "canceled"
-
["canceled", "danger"]
-
when "revoked"
-
["revoked", "danger"]
-
else
-
["pending issuance", pending]
-
end
-
end
-
-
def site_seal_status(site_seal)
-
case site_seal.workflow_state
-
when "new"
-
[SiteSeal::NEW_STATUS, 'danger']
-
when SiteSeal::FULLY_ACTIVATED.to_s
-
[SiteSeal::FULLY_ACTIVATED_STATUS, 'success']
-
when SiteSeal::CONDITIONALLY_ACTIVATED.to_s
-
[SiteSeal::CONDITIONALLY_ACTIVATED_STATUS, 'warning']
-
when SiteSeal::DEACTIVATED.to_s
-
[SiteSeal::DEACTIVATED_STATUS, 'danger']
-
when SiteSeal::CANCELED.to_s
-
[SiteSeal::CANCELED_STATUS, 'danger']
-
else
-
['','']
-
end
-
end
-
-
def bytesToSize(bytes)
-
sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
-
return '0 Byte' if (bytes == 0)
-
-
i = (Math.log(bytes) / Math.log(1024)).floor
-
return (bytes / (1024**i)).round(2).to_s + ' ' + sizes[i]
-
end
-
-
def getDocumentsPath(vh, path)
-
file_name = path[(path.rindex('/') + 1)..path.length]
-
param_style = file_name[0..(file_name.rindex('.') - 1)]
-
-
if vh.document_file_name.force_encoding('UTF-8').include?(file_name)
-
style = vh.document.default_style
-
else
-
style = param_style.to_sym
-
end
-
-
return vh.authenticated_s3_get_url :style=> style
-
end
-
-
def set_template(filename)
-
@template = File.join("api","v1","api_certificate_requests", filename)
-
end
-
end
-
require 'will_paginate/array'
-
-
class Api::V1::APIController < ActionController::API
-
include SerializerHelper
-
include ApplicationHelper
-
include ActionController::Cookies
-
include ActionController::HttpAuthentication::Basic::ControllerMethods
-
include ActionController::Rendering
-
include ActionController::ImplicitRender
-
include ActionView::Rendering
-
-
skip_before_action :verify_authenticity_token
-
before_filter :activate_authlogic
-
before_filter :set_default_request_format
-
after_filter :set_access_control_headers
-
-
TEST_SUBDOMAIN = 'sws-test'
-
PER_PAGE_DEFAULT = 10
-
-
respond_to :json
-
-
rescue_from MultiJson::DecodeError do |exception|
-
render text: exception.to_s, status: 422
-
end
-
-
private
-
-
def error(status, code, message)
-
json = {response_type: 'ERROR', response_code: code, message: message}.to_json
-
render json: json, status: status
-
end
-
-
def set_test
-
@test = is_sandbox? || %w{test}.include?(Rails.env)
-
end
-
-
def activate_authlogic
-
Authlogic::Session::Base.controller = Authlogic::ControllerAdapters::RailsAdapter.new(self)
-
end
-
-
def render_200_status_noschema
-
json = if @result.errors.empty?
-
serialize_model(@result)['data']['attributes']
-
else
-
{errors: @result.errors}
-
end
-
render json: json, status: 200
-
end
-
-
def render_200_status
-
render template: @template, status: 200
-
end
-
-
def render_400_status
-
render template: @template, status: 400
-
end
-
-
def render_500_error(e)
-
logger.error e.message
-
e.backtrace.each { |line| logger.error line }
-
error(500, 500, 'server error')
-
end
-
-
def set_access_control_headers
-
headers['Access-Control-Allow-Origin'] = '*'
-
headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
-
headers['Access-Control-Request-Method'] = '*'
-
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
-
end
-
-
def has_api_access?
-
ak = params[:account_key]
-
sk = params[:secret_key]
-
return false if ak.blank? || sk.blank?
-
@team ||= SslAccount.joins(:api_credential)
-
.where(api_credential: {account_key: ak, secret_key: sk}).last
-
!@team.nil?
-
end
-
-
def set_default_request_format
-
request.format = :json
-
end
-
end
-
class Api::V1::ApiSslManagerRequestsController < Api::V1::APIController
-
before_filter :set_test, :record_parameters
-
-
wrap_parameters ApiSslManagerRequest, include:
-
[*(
-
ApiSslManagerRequest::REGISTER+
-
ApiSslManagerRequest::DELETE+
-
ApiSslManagerRequest::COLLECTION+
-
ApiSslManagerRequest::COLLECTIONS
-
).uniq]
-
-
def set_result_parameter(result, asm, message = nil)
-
if message.nil?
-
result.ref = asm.ref
-
result.status = asm.api_status
-
result.reason = asm.reason unless asm.reason.blank?
-
else
-
result.status = message
-
end
-
end
-
-
def index
-
set_template "index"
-
-
if @result.save
-
@ssl_managers = @result.find_ssl_managers(params[:search])
-
-
page = params[:page] || 1
-
per_page = params[:per_page] || PER_PAGE_DEFAULT
-
@paged_ssl_managers = paginate @ssl_managers, per_page: per_page.to_i, page: page.to_i
-
-
if @paged_ssl_managers.is_a?(ActiveRecord::Relation)
-
@results = []
-
-
@paged_ssl_managers.each do |ssl_manager|
-
result = ApiSslManagerRetrieve.new(ref: ssl_manager.ref)
-
result.ip_address = ssl_manager.ip_address
-
result.mac_address = ssl_manager.mac_address
-
result.agent = ssl_manager.agent
-
result.friendly_name = ssl_manager.friendly_name
-
result.workflow_status = ssl_manager.workflow_status
-
result.created_at = ssl_manager.created_at
-
result.updated_at = ssl_manager.updated_at
-
-
@results << result
-
end
-
end
-
else
-
InvalidApiSslManagerRequest.create parameters: params, response: @result.to_json
-
end
-
-
render_200_status
-
rescue => e
-
render_500_error e
-
end
-
-
def register
-
set_template "register"
-
-
if @result.save
-
if @obj = @result.create_ssl_manager
-
if @obj.is_a?(RegisteredAgent) && @obj.errors.empty?
-
set_result_parameter(@result, @obj)
-
else
-
@result = @obj
-
end
-
end
-
else
-
InvalidApiSslManagerRequest.create parameters: params, response: @result.to_json
-
end
-
-
render_200_status
-
rescue => e
-
render_500_error e
-
end
-
-
def delete
-
set_template "delete"
-
-
if @result.save
-
if @obj = @result.delete_ssl_manager
-
if @obj.is_a?(String)
-
set_result_parameter(@result, nil, @obj)
-
else
-
@result = @obj
-
end
-
end
-
else
-
InvalidApiSslManagerRequest.create parameters: params, response: @result.to_json
-
end
-
-
render_200_status
-
rescue => e
-
render_500_error e
-
end
-
-
def collection
-
set_template "collection"
-
-
if @result.save
-
if @obj = @result.create_managed_certificates
-
if @obj.is_a?(RegisteredAgent) && @obj.errors.empty?
-
set_result_parameter(@result, @obj, nil)
-
else
-
@result = @obj
-
end
-
end
-
else
-
InvalidApiSslManagerRequest.create parameters: params, response: @result.to_json
-
end
-
-
render_200_status
-
rescue => e
-
render_500_error e
-
end
-
-
def collections
-
set_template "collections"
-
-
if @result.save
-
@managed_certs = @result.find_managed_certs(params[:ssl_manager_ref], params[:search])
-
-
page = params[:page] || 1
-
per_page = params[:per_page] || PER_PAGE_DEFAULT
-
@paged_managed_certs = paginate @managed_certs, per_page: per_page.to_i, page: page.to_i
-
-
if @paged_managed_certs.is_a?(ActiveRecord::Relation)
-
@results = []
-
-
@paged_managed_certs.each do |managed_cert|
-
result = ApiManagedCertificateRetrieve.new
-
result.common_name = managed_cert.common_name
-
result.subject_alternative_names = managed_cert.subject_alternative_names.split(',').join(', ')
-
result.effective_date = managed_cert.effective_date
-
result.expiration_date = managed_cert.expiration_date
-
result.serial = managed_cert.serial
-
result.issuer = managed_cert.issuer_dn
-
result.status = managed_cert.status
-
result.created_at = managed_cert.created_at
-
result.updated_at = managed_cert.updated_at
-
-
@results << result
-
end
-
end
-
else
-
InvalidApiSslManagerRequest.create parameters: params, response: @result.to_json
-
end
-
-
render_200_status
-
rescue => e
-
render_500_error e
-
end
-
-
private
-
-
def record_parameters
-
klass = case params[:action]
-
when "register"
-
ApiSslManagerCreate
-
when "collection"
-
ApiManagedCertificateCreate
-
when "collections"
-
ApiManagedCertificateRetrieve
-
when "delete"
-
ApiSslManagerDelete
-
when "index"
-
ApiSslManagerRetrieve
-
end
-
-
@result = klass.new(params[:api_ssl_manager_request] || _wrap_parameters(params)['api_ssl_manager_request'])
-
@result.debug = params[:debug] if params[:debug]
-
@result.action = params[:action]
-
@result.options = params[:options] if params[:options]
-
@result.test = @test
-
@result.request_url = request.url
-
@result.parameters = params.to_json
-
@result.raw_request = request.raw_post
-
@result.request_method = request.request_method
-
end
-
-
def set_template(filename)
-
@template = File.join("api","v1","api_ssl_manager_requests", filename)
-
end
-
end
-
class Api::V1::ApiUserRequestsController < Api::V1::APIController
-
before_filter :set_test, :record_parameters
-
-
wrap_parameters ApiUserRequest, include:
-
[*(ApiUserRequest::CREATE_ACCESSORS_1_4).uniq]
-
-
def set_result_parameters(result, aur, template)
-
result.login = aur.login
-
result.email = aur.email
-
result.account_number=aur.ssl_account.acct_number
-
result.status = aur.status
-
result.user_url = "#{api_domain}#{user_path(aur)}"
-
result.update_attribute :response, render_to_string(:template => template)
-
end
-
-
def create_v1_4
-
set_template "create_v1_4"
-
if @result.save
-
if @obj = @result.create_user
-
if @obj.is_a?(User) && @obj.errors.empty?
-
set_result_parameters(@result, @obj, @template)
-
@result.account_key=@obj.ssl_account.api_credential.account_key
-
@result.secret_key=@obj.ssl_account.api_credential.secret_key
-
else
-
@result = @obj #so that rabl can report errors
-
end
-
end
-
else
-
InvalidApiUserRequest.create parameters: params, response: @result.to_json
-
end
-
render_200_status
-
rescue => e
-
render_500_error e
-
end
-
-
def show_v1_4
-
set_template "show_v1_4"
-
if @result.save
-
if @obj = UserSession.create(params.to_h).user
-
# successfully charged
-
if @obj.is_a?(User) && @obj.errors.empty?
-
set_result_parameters(@result, @obj, @template)
-
@result.account_key=@obj.ssl_account.api_credential.account_key
-
@result.secret_key=@obj.ssl_account.api_credential.secret_key
-
@result.available_funds=Money.new(@obj.ssl_account.funded_account.cents).format
-
else
-
@result = @obj #so that rabl can report errors
-
end
-
else
-
@result.errors[:login] << "#{@result.login} not found or incorrect password"
-
end
-
else
-
InvalidApiUserRequest.create parameters: params, response: @result.errors.to_json
-
end
-
render_200_status
-
rescue => e
-
render_500_error e
-
end
-
-
def get_teams_v1_4
-
set_template "list_teams_v1_4"
-
if @result.save
-
if @obj = UserSession.create(params.to_h).user
-
@results = []
-
if @obj.is_a?(User) && @obj.errors.empty?
-
@obj.ssl_accounts.each do |team|
-
result = ApiUserListTeam_v1_4.new
-
result.acct_number = team.acct_number
-
result.roles = team.roles
-
result.created_at = team.created_at
-
result.updated_at = team.updated_at
-
result.status = team.status
-
result.ssl_slug = team.ssl_slug
-
result.company_name = team.company_name
-
result.issue_dv_no_validation = @obj.is_standard? || @obj.is_validations? ? team.issue_dv_no_validation : nil
-
result.billing_method = @obj.is_installer? && @obj.role_symbols.count == 1 ? nil : team.billing_method
-
result.available_funds = Money.new(team.funded_account.cents).format
-
result.currency = team.funded_account.currency
-
result.reseller_tier = team.reseller ? team.reseller.reseller_tier : nil
-
result.is_default_team = team.id == @obj.ssl_account.id ? true : false
-
@results << result
-
end
-
else
-
@result = @obj #so that rabl can report errors
-
end
-
else
-
@result.errors[:login] << "#{@result.login} not found or incorrect password"
-
end
-
else
-
InvalidApiUserRequest.create parameters: params, response: @result.errors.to_json
-
end
-
render_200_status
-
rescue => e
-
render_500_error e
-
end
-
-
def set_default_team_v1_4
-
set_template "set_default_team_v1_4"
-
if @result.save
-
if @obj = UserSession.create(params.to_h).user
-
@results = []
-
if @obj.is_a?(User) && @obj.errors.empty?
-
@ssl_account = SslAccount.find_by(acct_number: params[:acct_number])
-
if @obj.is_approved_account?(@ssl_account)
-
@obj.update_attribute(:default_ssl_account, @ssl_account.id)
-
@result.account_key = @obj.ssl_account.api_credential.account_key
-
@result.secret_key = @obj.ssl_account.api_credential.secret_key
-
else
-
@result.errors[:login] << "#{@result.login} not approved to #{params[:ssl_account_id]}"
-
end
-
else
-
@result = @obj #so that rabl can report errors
-
end
-
else
-
@result.errors[:login] << "#{@result.login} not found or incorrect password"
-
end
-
else
-
InvalidApiUserRequest.create parameters: params, response: @result.errors.to_json
-
end
-
render_200_status
-
rescue => e
-
render_500_error e
-
end
-
-
private
-
-
def record_parameters
-
klass = case params[:action]
-
when "create_v1_4", "update_v1_4"
-
ApiUserCreate_v1_4
-
when "show_v1_4"
-
ApiUserShow_v1_4
-
when "get_teams_v1_4"
-
ApiUserListTeam_v1_4
-
when "set_default_team_v1_4"
-
ApiUserSetDefaultTeam_v1_4
-
end
-
@result=klass.new(params[:api_certificate_request] || _wrap_parameters(params)['api_user_request'])
-
@result.debug = params[:debug] if params[:debug]
-
@result.action = params[:action]
-
@result.options = params[:options] if params[:options]
-
@result.test = @test
-
@result.request_url = request.url
-
@result.parameters = params.to_json
-
@result.raw_request = request.raw_post
-
@result.request_method = request.request_method
-
end
-
-
def set_template(filename)
-
@template = File.join("api","v1","api_user_requests", filename)
-
end
-
end
-
class Api::V1::TeamsController < Api::V1::APIController
-
-
before_filter :has_api_access?
-
-
def add_contact
-
@result = CertificateContact.create(params
-
.merge(contactable_id: @team.id, contactable_type: 'SslAccount')
-
.permit(permit_contact_params)
-
)
-
render_200_status_noschema
-
end
-
-
def add_registrant
-
@result = Registrant.create(params
-
.merge(contactable_id: @team.id, contactable_type: 'SslAccount')
-
.merge(registrant_type: Registrant::registrant_types.key(params[:registrant_type].to_i))
-
.permit(permit_contact_params.push(:registrant_type))
-
)
-
render_200_status_noschema
-
end
-
-
def add_billing_profile
-
@result = @team.billing_profiles.create(
-
params.permit(BillingProfile::REQUIRED_COLUMNS.map(&:to_sym))
-
)
-
render_200_status_noschema
-
end
-
-
def saved_contacts
-
json = serialize_models(@team.saved_contacts)
-
render json: json, status: 200
-
end
-
-
def saved_registrants
-
json = serialize_models(@team.saved_registrants)
-
render json: json, status: 200
-
end
-
-
private
-
-
def permit_contact_params
-
[
-
:title,
-
:first_name,
-
:last_name,
-
:company_name,
-
:department,
-
:po_box,
-
:address1,
-
:address2,
-
:address3,
-
:city,
-
:state,
-
:country,
-
:postal_code,
-
:email,
-
:phone,
-
:ext,
-
:fax,
-
:roles,
-
:contactable_id,
-
:contactable_type
-
]
-
end
-
end
-
class ApiCredentialsController < ApplicationController
-
before_filter :require_user
-
-
def new
-
end
-
-
def index
-
p = {:page => params[:page],per_page: 10}
-
set_apis
-
-
if params[:search]
-
search = params[:search].strip.split(" ")
-
role = nil
-
search.delete_if {|s|s =~ /role\:(.+)/; role ||= $1; $1}
-
search = search.join(" ")
-
@acs = @acs.with_role(role) if role
-
@acs = @acs.search(search) unless search.blank?
-
end
-
@acs = @acs.order("created_at desc").paginate(p)
-
-
respond_to do |format|
-
format.html { render :action => :index }
-
format.xml { render :xml => @acs }
-
end
-
end
-
-
def new
-
@ac=ApiCredential.new
-
end
-
-
def create
-
role_ids = params[:api_credential][:role_ids].reject(&:blank?)
-
params[:api_credential][:roles] = role_ids.to_json
-
params[:api_credential][:ssl_account_id] = current_user.ssl_account.id
-
params[:api_credential][:secret_key] = params[:api_credential][:acc_secret_key]
-
@ac = ApiCredential.new(params[:api_credential].except(:role_ids, :acc_id, :acc_secret_key))
-
@ac.save
-
redirect_to api_credentials_path(ssl_slug: @ssl_slug)
-
end
-
-
def edit
-
@ac = find_api_credential(params[:id])
-
if current_user.is_system_admins?
-
@user_accounts_roles = User.get_user_accounts_roles(@user)
-
end
-
@role_ids = @ac.role_ids
-
end
-
-
def update
-
role_ids = params[:api_credential][:role_ids].reject(&:blank?)
-
@ac = find_api_credential(params[:id])
-
@ac.account_key = params[:api_credential][:account_key]
-
@ac.secret_key = params[:api_credential][:acc_secret_key]
-
@ac.roles = role_ids.to_json
-
@ac.save
-
redirect_to api_credentials_path(ssl_slug: @ssl_slug)
-
end
-
-
def reset_credential
-
@ac = find_api_credential(params[:acc_id])
-
new_ac = ApiCredential.new
-
@ac.secret_key = new_ac.secret_key
-
@ac.save
-
respond_to do |format|
-
format.js {render json: new_ac.to_json}
-
end
-
end
-
-
def remove
-
@ac = find_api_credential(params[:id])
-
@ac.destroy
-
redirect_to api_credentials_path(ssl_slug: @ssl_slug)
-
end
-
-
private
-
-
def set_apis
-
if current_user.is_system_admins?
-
@acs = @ssl_account.try(:api_credentials) || ApiCredential.unscoped
-
else
-
@acs = current_user.manageable_acs
-
end
-
end
-
-
def find_api_credential(id)
-
if current_user.is_system_admins?
-
ApiCredential.find(id)
-
else
-
current_user.ssl_account.api_credentials.find(id)
-
end
-
end
-
end
-
# Filters added to this controller apply to all controllers in the application.
-
# Likewise, all the methods added will be available for all controllers.
-
-
1
class ApplicationController < ActionController::Base
-
1
rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_auth_token
-
1
layout 'application'
-
#include Authentication
-
1
include ApplicationHelper
-
1
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
1
rescue_from ActionController::RoutingError, :with => :not_found
-
1
rescue_from AbstractController::ActionNotFound, :with => :not_found
-
1
helper :all # include all helpers, all the time
-
1
protect_from_forgery # See ActionController::RequestForgeryProtection for details
-
1
helper_method :current_user_session, :current_user, :is_reseller, :cookies, :current_website,
-
:cart_contents, :cart_products, :certificates_from_cookie, "is_iphone?", "hide_dcv?", :free_qty_limit,
-
"hide_documents?", "hide_both?", "hide_validation?"
-
1
before_filter :set_database, if: "request.host=~/^sandbox/ || request.host=~/^sws-test/"
-
1
before_filter :set_mailer_host
-
1
before_filter :detect_recert, except: [:renew, :reprocess]
-
1
before_filter :set_current_user
-
1
before_filter :verify_duo_authentication, except: [:duo, :duo_verify, :login, :logout]
-
1
before_filter :identify_visitor, :record_visit,
-
if: "Settings.track_visitors"
-
1
before_filter :finish_reseller_signup, if: "current_user"
-
1
before_filter :team_base, if: "params[:ssl_slug] && current_user"
-
1
before_filter :set_ssl_slug, :load_notifications
-
1
after_filter :set_access_control_headers#need to move parse_csr to api, if: "request.subdomain=='sws' || request.subdomain=='sws-test'"
-
-
1
def set_access_control_headers
-
headers['Access-Control-Allow-Origin'] = '*'
-
headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
-
headers['Access-Control-Request-Method'] = '*'
-
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
-
end
-
-
1
def permission_denied
-
unless current_user
-
store_location
-
flash[:notice] = "You must be logged in to access this page"
-
redirect_to new_user_session_path
-
return false
-
else
-
flash[:error] = "You currently do not have permission to access that page."
-
redirect_to account_path
-
end
-
end
-
-
1
def paginated_scope(relation)
-
instance_variable_set "@#{controller_name}", relation.paginate(params[:page])
-
end
-
-
1
def is_reseller?
-
current_user && current_user.ssl_account.is_registered_reseller?
-
end
-
-
1
def save_user
-
@user.create_ssl_account([Role.get_owner_id])
-
@user.signup!(params)
-
@user.activate!(params)
-
-
# Check Code Signing Certificate Order for assign as assignee.
-
CertificateOrder.unscoped.search_validated_not_assigned(@user.email).each do |cert_order|
-
cert_order.update_attribute(:assignee, @user)
-
LockedRecipient.create_for_co(cert_order)
-
end
-
-
@user.deliver_activation_confirmation!
-
@user_session = UserSession.create(@user)
-
@current_user_session = @user_session
-
Authorization.current_user = @current_user = @user_session.record
-
end
-
-
1
def verify_duo_authentication
-
if current_user
-
if current_user.is_duo_required?
-
if !session[:duo_auth]
-
redirect_to duo_user_session_path
-
end
-
else
-
if current_user.ssl_account.sec_type == 'duo' && current_user.duo_enabled
-
if Settings.duo_auto_enabled || Settings.duo_custom_enabled
-
if !session[:duo_auth]
-
redirect_to duo_user_session_path
-
end
-
end
-
end
-
end
-
end
-
end
-
-
1
def find_tier
-
@tier =''
-
tier_label = ->(label){"#{'-' unless label =~/\A\d\z/}"+label + 'tr'} #add '-' for non single digit tier due to flexible labeling
-
if @certificate_order and !@certificate_order.ssl_account.try(:tier_suffix).blank?
-
@tier = @certificate_order.ssl_account.tier_suffix
-
elsif current_user and current_user.ssl_account.tier_suffix
-
@tier = current_user.ssl_account.tier_suffix
-
elsif cookies[ResellerTier::TIER_KEY]
-
@tier = ResellerTier.tier_suffix(cookies[ResellerTier::TIER_KEY])
-
end
-
@tier = nil if @tier.blank?
-
@tier
-
end
-
-
1
def add_to_cart line_item
-
session[:cart_items] << line_item.model_and_id
-
end
-
-
1
def apply_discounts(order)
-
if (params[:discount_code])
-
order.temp_discounts =[]
-
general_discount = Discount.viable.general.find_by_ref(params[:discount_code])
-
if current_user and !current_user.is_system_admins?
-
if current_user.ssl_account.discounts.find_by_ref(params[:discount_code])
-
order.temp_discounts<<current_user.ssl_account.discounts.find_by_ref(params[:discount_code]).id
-
elsif general_discount
-
order.temp_discounts<<general_discount.id
-
end
-
elsif general_discount
-
order.temp_discounts<<general_discount.id
-
end
-
end
-
end
-
-
# returns the cart cookie with reseller tier as an array
-
1
def cart_contents
-
find_tier
-
cart = cookies[ShoppingCart::CART_KEY]
-
cart.blank? ? {} : JSON.parse(cart).each{|i|i['pr']=i['pr']+@tier if(i && @tier && i['pr'] && !i['pr'].ends_with?(@tier))}
-
end
-
-
1
def cart_products
-
cart_contents.collect {|cart_item|
-
pr = cart_item[ShoppingCart::PRODUCT_CODE]
-
if pr.blank?
-
nil
-
else
-
ActiveRecord::Base.find_from_model_and_id(pr)
-
end
-
}.compact
-
end
-
-
1
def delete_cart_items
-
cookies.delete ShoppingCart::CART_KEY, domain: cookie_domain
-
end
-
-
1
def save_cart_items(items)
-
set_cookie(ShoppingCart::CART_KEY,JSON.generate(items))
-
end
-
-
1
def free_qty_limit
-
qty=current_user ?
-
Certificate::FREE_CERTS_CART_LIMIT - current_user.ssl_account.cached_certificate_orders.unused_free_credits.count :
-
Certificate::FREE_CERTS_CART_LIMIT
-
(qty <= 0) ? 0 : qty
-
end
-
-
# parse the cookie and build @certificate_orders
-
1
def certificates_from_cookie
-
certs=cart_contents
-
@certificate_orders=[]
-
return @certificate_orders if certs.blank?
-
limit=free_qty_limit
-
Order.certificates_order(certificates: certs, max_free: limit,
-
certificate_orders: @certificate_orders, current: current_user)
-
end
-
-
1
def old_certificates_from_cookie
-
@certificate_orders=[]
-
return @certificate_orders unless cookies[ShoppingCart::CART_KEY]
-
Order.cart_items session, cookies
-
certs=cookies[ShoppingCart::CART_KEY].split(":")
-
certs.each do |c|
-
parts = c.split(",")
-
certificate_order = CertificateOrder.new :server_licenses=>parts[2],
-
:duration=>parts[1], :quantity=>parts[4].to_i
-
certificate_order.certificate_contents.build :domains=>parts[3]
-
certificate = Certificate.for_sale.find_by_product(parts[0])
-
unless current_user.blank?
-
current_user.ssl_account.clear_new_certificate_orders
-
next unless current_user.ssl_account.can_buy?(certificate)
-
end
-
#adjusting duration to reflect number of days validity
-
duration = certificate.duration_in_days(certificate_order.duration)
-
certificate_order.certificate_contents[0].duration = duration
-
if certificate.is_ucc? || certificate.is_wildcard?
-
psl = certificate.items_by_server_licenses.find{|item|
-
item.value==duration.to_s}
-
so = SubOrderItem.new(:product_variant_item=>psl,
-
:quantity=>certificate_order.server_licenses.to_i,
-
:amount=>psl.amount*certificate_order.server_licenses.to_i)
-
certificate_order.sub_order_items << so
-
if certificate.is_ucc?
-
pd = certificate.items_by_domains.find_all{|item|
-
item.value==duration.to_s}
-
additional_domains = (certificate_order.domains.try(:size) || 0) - Certificate::UCC_INITIAL_DOMAINS_BLOCK
-
so = SubOrderItem.new(:product_variant_item=>pd[0],
-
:quantity=>Certificate::UCC_INITIAL_DOMAINS_BLOCK,
-
:amount=>pd[0].amount*Certificate::UCC_INITIAL_DOMAINS_BLOCK)
-
certificate_order.sub_order_items << so
-
if additional_domains > 0
-
so = SubOrderItem.new(:product_variant_item=>pd[1],
-
:quantity=>additional_domains,
-
:amount=>pd[1].amount*additional_domains)
-
certificate_order.sub_order_items << so
-
end
-
end
-
end
-
unless certificate.is_ucc?
-
pvi = certificate.items_by_duration.find{|item|item.value==duration.to_s}
-
so = SubOrderItem.new(:product_variant_item=>pvi, :quantity=>1,
-
:amount=>pvi.amount)
-
certificate_order.sub_order_items << so
-
end
-
certificate_order.amount = certificate_order.sub_order_items.map(&:amount).sum
-
certificate_order.certificate_contents[0].
-
certificate_order = certificate_order
-
@certificate_orders << certificate_order if certificate_order.valid?
-
end
-
end
-
-
1
def find_certificate
-
prod = params[:id]=='mssl' ? 'high_assurance' : params[:id]
-
@certificate = Certificate.includes(:product_variant_items).for_sale.find_by_product(prod+(@tier || ''))
-
end
-
-
1
def find_certificate_orders(options={})
-
return CertificateOrder.none unless current_user # returns null set. Rails 4 is CertificateOrder.none
-
@search = params[:search] || ""
-
if is_sandbox? and @search.include?("is_test:true").blank?
-
@search << " is_test:true"
-
end
-
-
result = if !@search.blank?
-
(current_user.is_admin? ?
-
(CertificateOrder.unscoped{
-
(@ssl_account.try(:cached_certificate_orders) || CertificateOrder).search_with_csr(params[:search], options)
-
}) :
-
(current_user.role_symbols(current_user.ssl_account)==[Role::INDIVIDUAL_CERTIFICATE.to_sym] ?
-
(current_user.ssl_account.cached_certificate_orders.search_assigned(current_user.id).search_with_csr(params[:search], options)) :
-
(current_user.ssl_account.cached_certificate_orders.search_with_csr(params[:search], options))
-
)
-
)
-
else
-
(current_user.is_admin? ?
-
(@ssl_account.try(:cached_certificate_orders) || CertificateOrder).not_test.not_new(options) :
-
(current_user.role_symbols(current_user.ssl_account)==[Role::INDIVIDUAL_CERTIFICATE.to_sym] ?
-
(current_user.ssl_account.cached_certificate_orders.not_test.not_new(options).search_assigned(current_user.id)) :
-
(current_user.ssl_account.cached_certificate_orders.not_test.not_new(options))
-
)
-
)
-
end.order(params[:order]=="by_csr" ? "csrs.created_at desc" : "certificate_orders.created_at desc")
-
result=result.joins{certificate_contents.csr} if params[:order]=="by_csr"
-
if options[:source] && options[:source] == 'folders'
-
archived_folder = current_user.is_admin? || (params[:search] && params[:search].include?('folder_ids')) ?
-
[true, false, nil] : [false, nil]
-
result=result.includes(:folder).where(folders: {archived: archived_folder})
-
end
-
result
-
end
-
-
1
def find_certificate_orders_with_site_seals
-
return CertificateOrder.where('1=0') unless current_user # returns null set. Rails 4 is CertificateOrder.none
-
if @search = params[:search]
-
(current_user.is_admin? ?
-
(CertificateOrder.search_with_csr(params[:search])) :
-
current_user.certificate_orders.
-
search_with_csr(params[:search])).has_csr
-
else
-
(current_user.is_admin? ?
-
CertificateOrder.not_new(:include=>:site_seal) :
-
current_user.certificate_orders.not_new(:include=>:site_seal))
-
end
-
end
-
-
1
def set_cookie(name,value)
-
# cookies.delete(name, domain: "secure.ssl.local") if name==:cart
-
cookies[name] = {value: value, path: "/", domain: :all,
-
expires: Settings.cart_cookie_days.to_i.days.from_now}
-
end
-
-
1
def set_ssl_slug(target_user=nil)
-
user = target_user || current_user
-
if user
-
ssl = user.ssl_account
-
@ssl_slug = if user.is_system_admins?
-
nil
-
else
-
if ssl
-
ssl.ssl_slug || ssl.acct_number
-
end
-
end
-
end
-
guest_enrollment if user.nil?
-
end
-
-
1
def not_found
-
render 'site/404_not_found', status: 404
-
end
-
-
1
protected
-
-
1
def guest_enrollment
-
if %w[enrollment_links].include? action_name
-
@ssl_slug = params[:ssl_slug]
-
end
-
end
-
-
1
def set_prev_flag
-
@prev=true if params["prev.x".intern]
-
end
-
-
1
def prep_certificate_orders_instances
-
if params[:certificate_order]
-
@certificate = Certificate.for_sale.find_by_product(params[:certificate][:product])
-
co_valid = certificate_order_steps
-
if params["prev.x".intern] || !co_valid
-
@certificate_order.has_csr=true
-
render(:template => "/certificates/buy", :layout=>"application")
-
return false
-
end
-
else
-
unless params["prev.x".intern].nil?
-
redirect_to show_cart_orders_url and return
-
return false
-
end
-
certificates_from_cookie
-
end
-
end
-
-
1
def set_current_user
-
Authorization.current_user = current_user
-
if current_user and current_user.ssl_accounts.blank?
-
current_user_session.destroy
-
Authorization.current_user=nil
-
return false
-
end
-
end
-
-
1
def setup_orders
-
#will create @certificate_orders below
-
certificates_from_cookie
-
@order = Order.new(:amount=>(current_order.amount.to_s.to_i or 0))
-
@order.add_certificate_orders(@certificate_orders)
-
end
-
-
1
def parse_certificate_orders
-
if params[:certificate_order]
-
@certificate_order = current_user.ssl_account.certificate_orders.current
-
@order = current_order
-
else
-
setup_orders
-
end
-
end
-
-
1
def go_back_to_buy_certificate
-
#need to create new objects and delete the existing ones
-
@certificate_order = current_user.ssl_account.
-
certificate_orders.detect(&:new?)
-
@certificate = @certificate_order.certificate
-
@certificate_content = @certificate_order.certificate_content.dup
-
@certificate_order = current_user.ssl_account.
-
certificate_orders.detect(&:new?).dup
-
@certificate_order.duration = @certificate.duration_index(@certificate_content.duration)
-
@certificate_order.has_csr = true
-
render(:template => "/certificates/buy", :layout=>"application")
-
end
-
-
1
def create_ssl_certificate_route(user)
-
# if params[:certificate]
-
# user.ssl_account.is_registered_reseller? ?
-
# ["submit", certificate_orders_url] : ["redirect", new_order_url]
-
## elsif params[:free_certificate]
-
## create_free_ssl_orders_path
-
## elsif params[:free_certificates]
-
## create_multi_free_ssl_orders_path
-
## else #assume non-free certificates
-
# end
-
if user.ssl_account.is_registered_reseller?
-
["submit", params[:certificate] ? certificate_orders_url : new_order_url]
-
else
-
if params[:certificate] && params[:certificate][:product]
-
#assume a single cert sale
-
params[:certificate][:product]=="free" ? ["submit", ""] : ["",""]
-
else
-
#shopping cart checkout
-
shopping_cart_amount > 0 ? ["",""] : ["submit", ""]
-
end
-
# ["redirect", new_order_url]
-
end
-
end
-
-
1
def shopping_cart_amount
-
certificates_from_cookie.sum(&:amount)
-
end
-
-
#co - certificate order
-
1
def hide_validation?(co)
-
if current_user.blank?
-
true
-
else
-
!co.certificate_content.show_validation_view?
-
end
-
end
-
-
=begin
-
def responder
-
EnhancedResponder
-
end
-
=end
-
-
1
def handle_unverified_request
-
# raise an exception
-
fail ActionController::InvalidAuthenticityToken
-
# or destroy session, redirect
-
if current_user_session
-
current_user_session.destroy
-
end
-
redirect_to root_url
-
end
-
-
1
def invalid_auth_token
-
render :text => "Invalid authentication token. Please restart session or go to #{root_url} to start a new session.", :status => 422
-
end
-
-
#derive the model name from the controller. egs UsersController will return User
-
1
def self.permission
-
return name = self.name.gsub('Controller','').singularize.split('::').last.constantize.name rescue nil
-
end
-
-
1
def current_ability
-
@current_ability ||= Ability.new(current_user)
-
end
-
-
#load the permissions for the current user so that UI can be manipulated
-
1
def load_permissions
-
@current_permissions = current_user.permissions.collect{|i| [i.subject_class, i.action]}
-
end
-
-
1
def find_ssl_account
-
ssl_acct_slug = params[:ssl_slug] || params[:acct_number] ||
-
(params[:certificate_enrollment_request][:ssl_slug] if params[:certificate_enrollment_request])
-
if params[:action]=="dcv_all_validate" and ssl_acct_slug
-
@ssl_account = SslAccount.find_by_acct_number(ssl_acct_slug) ||
-
SslAccount.find_by_ssl_slug(ssl_acct_slug)
-
not_found if @ssl_account.blank?
-
elsif current_user.blank?
-
not_found
-
else
-
@ssl_account = if ssl_acct_slug and request[:action]!="validate_ssl_slug"
-
ssls = current_user.is_system_admins? ? SslAccount : current_user.ssl_accounts
-
ssls.find_by_acct_number(ssl_acct_slug) || ssls.find_by_ssl_slug(ssl_acct_slug)
-
else
-
current_user.ssl_account
-
end
-
not_found if @ssl_account.blank?
-
end
-
end
-
-
1
def load_notifications
-
if current_user
-
if current_user.pending_account_invites?
-
@team_invites = []
-
current_user.get_pending_accounts.each do |invite|
-
new_params = {ssl_account_id: invite[:ssl_account_id], token: invite[:approval_token], to_teams: true}
-
invite[:accept] = approve_account_invite_user_path(current_user, new_params)
-
invite[:decline] = decline_account_invite_user_path(current_user, new_params)
-
invite.delete(:approval_token)
-
@team_invites << invite
-
end
-
end
-
if current_user.persist_notice && current_user.assignments.where.not(role_id: Role.cannot_be_invited)
-
flash[:info_activation] = true
-
end
-
end
-
end
-
-
1
def u2f
-
@u2f ||= U2F::U2F.new(request.base_url)
-
end
-
-
1
private
-
-
1
def get_team_tags
-
unless @team_tags
-
@team_tags = if @taggable
-
Tag.get_object_team_tags(@taggable)
-
elsif current_user.is_system_admins?
-
Tag.all.order(taggings_count: :desc)
-
elsif @ssl_account || ssl_account
-
(@ssl_account || ssl_account).tags.order(name: :asc)
-
else
-
[]
-
end
-
end
-
end
-
-
#Saves a cookie using a hash
-
# <tt>options</tt> - Contains keys name, value (a hash), path, and expires
-
1
def save_cookie(options)
-
c={:value=>JSON.generate(options[:value]), :path => options[:path],
-
:expires => options[:expires]}
-
c.merge!(:domain=>options[:domain]) if options[:domain]
-
cookies[options[:name]] = c
-
end
-
-
1
def get_cookie(name)
-
name = name.to_sym if name.is_a? String
-
cookies[name].blank? ? {} : JSON.parse(cookies[name])
-
end
-
-
# if in process of recerting (renewal, reprocess, etc), this sets instance
-
# variables from params. Only one type allowed at a time.
-
1
def detect_recert
-
CertificateOrder::RECERTS.each do |r|
-
unless params[r.to_sym].blank?
-
recert=CertificateOrder.find_by_ref(params[r.to_sym])
-
instance_variable_set("@#{r.to_sym}", recert) if recert
-
break
-
end
-
end
-
end
-
-
1
def current_user_session
-
return @current_user_session if defined?(@current_user_session)
-
@current_user_session = UserSession.find(:shadow).try(:user) ? UserSession.find(:shadow) : UserSession.find
-
end
-
-
1
def current_user
-
return @current_user if defined?(@current_user)
-
@current_user = current_user_session && current_user_session.user
-
end
-
-
1
def require_user
-
if current_user.blank?
-
store_location
-
flash[:notice] = "You must be logged in to access this page"
-
redirect_to new_user_session_path
-
return false
-
end
-
end
-
-
1
def require_admin
-
user_not_authorized unless current_user.is_admin?
-
end
-
-
1
def require_no_user
-
if current_user
-
store_location
-
set_cookie(:acct,current_user.ssl_account.acct_number)
-
flash[:notice] = "You must be logged out to access page '#{request.fullpath}'"
-
redirect_to account_url
-
return false
-
end
-
end
-
-
1
def go_prev
-
unless params["prev.x".intern].nil?
-
if params[:certificate_order]
-
go_back_to_buy_certificate
-
else
-
redirect_to(show_cart_orders_url)
-
end
-
false
-
end
-
end
-
-
1
def store_location
-
session[:return_to] = request.url
-
end
-
-
1
def redirect_back_or_default(default)
-
go_to = (session[:return_to] == logout_path) ? nil : session[:return_to]
-
session[:return_to] = nil
-
redirect_to(go_to || default)
-
end
-
-
1
def finish_reseller_signup
-
blocked = %w(certificate_orders orders site_seals validations ssl_accounts users)
-
if current_user.is_reseller? and current_user.ssl_account.is_new_reseller?
-
redirect_to new_account_reseller_url and return if
-
(current_user.ssl_account.reseller ?
-
# following line avoids loop with last condition in ResellersController#new comparing reseller.complete?
-
# with ssl_account.is_new_reseller?
-
!current_user.ssl_account.reseller.complete? :
-
current_user.ssl_account.is_new_reseller?) and blocked.include?(controller_name)
-
end
-
end
-
-
1
def user_not_authorized
-
render 'site/403_forbidden', status: 403
-
end
-
-
1
def save_billing_profile
-
profile = current_user.ssl_account.billing_profiles.find_by_card_number @billing_profile.card_number
-
current_user.ssl_account.billing_profiles.delete profile unless profile.nil?
-
current_user.ssl_account.billing_profiles << @billing_profile
-
end
-
-
#this is a band-aid function to make sure the number of item in cookies
-
#aid_li and cart match. however, the problem causing the unsync was found.
-
#this function can be turned back on by the Settings.sync_aid_li_and_cart
-
#variable
-
1
def sync_aid_li_and_cart
-
if cookies[ShoppingCart::AID_LI] && cookies[ShoppingCart::CART_KEY]
-
aid_li=cookies[ShoppingCart::AID_LI].split(":")
-
cart=cart_contents
-
if aid_li.count!=cart.count
-
if aid_li.count>cart.count
-
(aid_li.count-cart.count).times do
-
aid_li.pop
-
end
-
elsif aid_li.count<cart.count
-
(cart.count-aid_li.count).times do
-
aid_li.push(aid_li.last)
-
end
-
end
-
set_cookie(ShoppingCart::AID_LI,aid_li.join(":"))
-
set_cookie(ShoppingCart::CART_KEY,cart.join(":"))
-
end
-
end
-
end
-
-
1
def clear_cart
-
cookies.delete(ShoppingCart::CART_KEY)
-
cookies.delete(ShoppingCart::AID_LI)
-
current_user.shopping_cart.update_attribute(:content, nil) if current_user && current_user.shopping_cart
-
end
-
-
1
def validation_destination(options)
-
co = options[:certificate_order]
-
slug = options[:ssl_slug]
-
co.certificate.is_code_signing? ?
-
document_upload_certificate_order_validation_url(certificate_order_id: co.ref) :
-
new_certificate_order_validation_path(*[slug, co.ref].compact)
-
end
-
-
1
def identify_visitor
-
cookies[VisitorToken::GUID] = {:value=>UUIDTools::UUID.random_create.to_s, :path => "/",
-
:expires => 2.years.from_now} unless cookies[VisitorToken::GUID]
-
@visitor_token = VisitorToken.find_or_create_by_guid_and_affiliate_id(
-
cookies[VisitorToken::GUID],cookies[ShoppingCart::AID])
-
@visitor_token.user ||= current_user if current_user
-
@visitor_token.save if @visitor_token.changed? #TODO only if change
-
end
-
-
1
def record_visit
-
return if request.method.downcase != "get"
-
md5_current = Digest::MD5.hexdigest(request.url)
-
if request.referer
-
md5_previous = Digest::MD5.hexdigest(request.referer)
-
end
-
cur = TrackedUrl.find_or_create_by_md5_and_url(md5_current,request.url)
-
prev = request.referer ? TrackedUrl.find_or_create_by_md5_and_url(md5_previous,request.referer) : nil
-
Tracking.create(:referer=>prev,:visitor_token=>@visitor_token,
-
:tracked_url=>cur, remote_ip: request.remote_ip)
-
# output = cache(md5) { request.request_uri }
-
# if @visitor
-
# md5 = Digest::MD5.hexdigest(request.request_uri)
-
# output = cache(md5) { request.request_uri }
-
#
-
# @tracking = UUID.random_create
-
# cookies[VisitorToken::GUID] = {:value=>guid, :path => "/", :expires => 2.years.from_now} unless cookies[VisitorToken::GUID]
-
# @visitor_token = VisitorToken.find_or_build_by_guid(cookies[VisitorToken::GUID])
-
# @visitor_token.user ||= current_user if current_user
-
# @visitor_token.affiliate_id = cookies[ShoppingCart::AID] if cookies[ShoppingCart::AID] && token.affiliate_id != cookies[ShoppingCart::AID]
-
# @visitor_token.save
-
# end
-
end
-
-
#Surl related functions
-
1
def add_link_to_cookie(guid)
-
guids=get_guids
-
guids << guid.to_s
-
save_links_cookie({guid: guids.compact.join(","), v: Surl::COOKIE_VERSION})
-
end
-
-
1
def remove_link_from_cookie(guid)
-
guids=get_guids
-
unless guids.blank? || guids.include?(guid)
-
guids.delete guid
-
end
-
save_links_cookie({guid: guids.compact.join(","), v: Surl::COOKIE_VERSION})
-
end
-
-
1
def get_valid_surls(page=nil)
-
requested=get_guids
-
guids=page.blank? ? Surl.where{guid >> requested} :
-
Surl.where{guid >> requested}.paginate(page)
-
unless guids.empty?
-
(requested - guids.map(&:guid)).map do |g|
-
remove_link_from_cookie(g)
-
end
-
guids.select{|surl|surl.status==Surl::REMOVE}.each do |g|
-
remove_link_from_cookie(g)
-
end
-
end
-
guids
-
end
-
-
1
def get_guids
-
upgrade_cookie
-
links=get_cookie("links2")
-
guids=links.blank? ? [] : links["guid"].split(",")
-
end
-
-
#renaming cookie from links to links2
-
1
def upgrade_cookie
-
links=get_cookie(:links)
-
unless links.blank?
-
guids = links['guid']
-
cookies.delete(:links)# if request.subdomains.last=="links"
-
save_links_cookie({guid: guids, v: Surl::COOKIE_VERSION})
-
end
-
end
-
-
1
def save_links_cookie(value)
-
save_cookie name: Surl::COOKIE_NAME, value: value, path: "/",
-
expires: 2.years.from_now, domain: ".ssl.com"
-
end
-
-
1
def record_surl_visit
-
SurlVisit.create visitor_token: @visitor_token,
-
surl: @surl,
-
referer_host: request.env['REMOTE_HOST'],
-
referer_address: request.env['REMOTE_ADDR'],
-
request_uri: request.url,
-
http_user_agent: request.env['HTTP_USER_AGENT'],
-
result: @render_result
-
end
-
-
1
def record_order_visit(order)
-
order.update_attribute :visitor_token, @visitor_token if @visitor_token
-
end
-
-
1
def assign_ssl_links(user)
-
get_valid_surls.each do |surl|
-
if surl.user.blank?
-
user.surls<<surl
-
end
-
end
-
end
-
-
1
def is_iphone?
-
return false if request.env['HTTP_USER_AGENT'].blank?
-
ua = request.env['HTTP_USER_AGENT'].downcase
-
ua =~ /iphone|itouch|ipod/
-
end
-
-
1
def is_client_windows?
-
(request.env['HTTP_USER_AGENT'] =~ /windows/i)
-
end
-
-
1
%W(email login).each do |u|
-
2
define_method("find_dup_#{u}") do
-
is_new_session = params[:user_session]
-
attr=is_new_session.blank? ? params[u.to_sym] : is_new_session[u.to_sym]
-
@dup=DuplicateV2User.send("find_by_#{u}", attr) unless
-
User.send("find_by_#{u}", attr)
-
unless @dup.blank?
-
flash.now[:error]="Ooops, #{u=="email" ? @dup.email : @dup.login} has been consolidated with a primary account.
-
Please contact support@ssl.com for assistance or more information." unless request.xhr?
-
if is_new_session
-
DuplicateV2UserMailer.attempted_login_by(@dup).deliver
-
@user_session = UserSession.new(:login=>is_new_session[u.to_sym].to_h)
-
else
-
DuplicateV2UserMailer.duplicates_found(@dup, u).deliver
-
end
-
respond_to do |format|
-
format.html {render action: :new}
-
#assume checkout
-
format.js {render :json=>@dup}
-
end
-
end
-
end
-
end
-
-
1
def hide_dcv?
-
@other_party_validation_request && @other_party_validation_request.hide_dcv?
-
end
-
-
1
def hide_documents?
-
@other_party_validation_request && @other_party_validation_request.hide_documents?
-
end
-
-
1
def hide_both?
-
@other_party_validation_request && @other_party_validation_request.hide_both?
-
end
-
-
1
def error(status, code, message)
-
render :js => {:response_type => "ERROR", :response_code => code, :message => message}.to_json, :status => status
-
end
-
-
1
def team_base
-
@ssl_account = SslAccount.where('ssl_slug = ? OR acct_number = ?', params[:ssl_slug], params[:ssl_slug]).first
-
if current_user.get_all_approved_accounts.include?(@ssl_account)
-
current_user.set_default_ssl_account(@ssl_account)
-
end unless current_user.is_system_admins?
-
end
-
-
1
def is_sandbox_or_test?
-
host = ActionMailer::Base.default_url_options[:host]
-
sandbox = (request && request.try(:subdomain)=='sandbox') or !Sandbox.current_site(request.host).blank?
-
sandbox || host=~/^sandbox\./ || host=~/^sws-test\./
-
end
-
-
1
class Helper
-
1
include Singleton
-
1
include ActionView::Helpers::NumberHelper
-
end
-
end
-
class AuthenticationsController < ApplicationController
-
def create
-
omniauth = request.env['omniauth.auth']
-
authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
-
-
if authentication
-
# User is already registered with application
-
flash[:info] = 'Signed in successfully.'
-
sign_in_and_redirect(authentication.user)
-
elsif current_user
-
# User is signed in but has not already authenticated with this social network
-
current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid'])
-
current_user.apply_omniauth(omniauth)
-
current_user.save
-
-
flash[:info] = 'Authentication successful.'
-
redirect_to home_url
-
else
-
# User is new to this application
-
user = User.new
-
user.authentications.build(:provider => omniauth['provider'], :uid => omniauth['uid'])
-
user.apply_omniauth(omniauth)
-
-
if user.save
-
flash[:info] = 'User created and signed in successfully.'
-
sign_in_and_redirect(user)
-
else
-
session[:omniauth] = omniauth.except('extra')
-
redirect_to signup_path
-
end
-
end
-
end
-
-
def destroy
-
@authentication = current_user.authentications.find(params[:id])
-
@authentication.destroy
-
flash[:notice] = 'Successfully destroyed authentication.'
-
redirect_to authentications_url
-
end
-
-
private
-
def sign_in_and_redirect(user)
-
unless current_user
-
user_session = UserSession.new((User.find_by_single_access_token(user.single_access_token)))
-
user_session.save
-
end
-
redirect_to home_path
-
end
-
end
-
class BillingProfilesController < ApplicationController
-
include ApplicationHelper, OrdersHelper
-
#ssl_required :new
-
#helper :profile
-
before_filter :require_user, :find_ssl_account
-
filter_access_to :all
-
filter_access_to :destroy, attribute_check: true
-
respond_to :json
-
-
def index
-
@billing_profile = BillingProfile.new
-
p = {:page => params[:page]}
-
unpaginated =
-
if @search = params[:search]
-
if current_user.is_system_admins?
-
(@ssl_account.try(:billing_profiles) ? BillingProfile.unscoped{@ssl_account.try(:billing_profiles)} :
-
BillingProfile.unscoped).search(params[:search])
-
else
-
current_user.ssl_account.billing_profiles.search(params[:search])
-
end
-
else
-
if current_user.is_system_admins?
-
(@ssl_account.try(:billing_profiles) ? BillingProfile.unscoped{@ssl_account.try(:billing_profiles)} : BillingProfile.unscoped).order("created_at desc")
-
else
-
current_user.ssl_account.billing_profiles
-
end
-
end
-
@billing_profiles=unpaginated.paginate(p)
-
respond_to do |format|
-
format.html { render :action => :index}
-
format.xml { render :xml => @billing_profiles }
-
end
-
end
-
-
def destroy
-
@bp=BillingProfile.find(params[:id])
-
@bp.update_column :status, "disable"
-
respond_with @bp
-
end
-
-
def new
-
@billing_profile=BillingProfile.new
-
end
-
-
def update
-
bp = @ssl_account.billing_profiles.find_by(id: params[:id])
-
if bp && params[:set_default]
-
if bp.update(default_profile: true)
-
flash[:notice] = "Succesfully set billing profile ending in #{bp.last_digits} to default"
-
end
-
end
-
redirect_to billing_profiles_path(@ssl_slug)
-
end
-
-
def create
-
@billing_profile = @ssl_account.billing_profiles.build(params[:billing_profile])
-
if @billing_profile.save
-
flash[:notice] = "Billing Profile successfully created!"
-
if params[:manage_billing_profiles]
-
redirect_to :back
-
else
-
redirect_to account_path
-
end
-
else
-
if params[:manage_billing_profiles]
-
@billing_profiles = @ssl_account.billing_profiles
-
render :index
-
else
-
render :new
-
end
-
end
-
end
-
end
-
require 'securerandom'
-
-
class CdnsController < ApplicationController
-
include HTTParty
-
before_action :set_cdn, only: [:show, :update, :destroy]
-
before_action :require_user, only: [:index, :register_account, :resource_cdn, :update_custom_domain]
-
before_action :set_tab_name, only: [:resource_cdn, :update_resource, :add_custom_domain, :update_advanced_setting,
-
:update_custom_domain, :purge_cache, :update_cache_expiry, :delete_resource]
-
-
before_action :set_row_page, only: [:index]
-
-
# before_filter :require_user, only: [:index, :register_account, :resource_cdn, :update_custom_domain]
-
-
# filter_access_to :all
-
# filter_access_to :index, :resource_cdn, require: :read
-
# filter_access_to :create, :register_account, :add_custom_domain, require: :new
-
# filter_access_to :update_resource, :update_advanced_setting, :update_cache_expiry, require: :update
-
# filter_access_to :update_resources, :purge_cache, :delete_resource, require: :delete
-
# filter_access_to :update_custom_domain, require: [:new, :update, :delete]
-
-
DUPLICATE_CUSTOM_DOMAIN = "This custom domain is already in use."
-
-
# # GET /cdns
-
# # GET /cdns.json
-
def index
-
@results = {}
-
-
if current_user.ssl_account
-
@response = current_user.is_system_admins? ?
-
HTTParty.get('https://reseller.cdnify.com/api/v1/resources/all-reseller-resources',
-
basic_auth: {username: current_user_api_key, password: 'x'}) :
-
HTTParty.get('https://reseller.cdnify.com/api/v1/resources',
-
basic_auth: {username: current_user_api_key, password: 'x'})
-
-
if @response && @response.code == 200
-
resources = @response.parsed_response['resources'].sort_by {|resource| resource['created_at']}.reverse
-
@results[:resources] = resources.paginate(@p)
-
else
-
@results[:resources] = [].paginate(@p)
-
end
-
end
-
-
respond_to do |format|
-
format.html { render :action => :index }
-
format.xml { render :xml => @results }
-
end
-
end
-
-
def register_account
-
returnObj = {}
-
if current_user.ssl_account
-
reseller_api_key = Rails.application.secrets.cdnify_reseller_api_key
-
-
email_addr = current_user.ssl_account.acct_number + '@ssl.com'
-
email_addr = 'sandbox-' + email_addr if is_sandbox?
-
password = SecureRandom.hex(32)
-
-
@response = HTTParty.post('https://reseller.cdnify.com/users',
-
{basic_auth: {username: reseller_api_key, password: 'x'}, body: {email: email_addr, password: password}})
-
-
if @response &&
-
@response.parsed_response &&
-
@response.parsed_response['users'] &&
-
@response.parsed_response['users'].length > 0
-
returnObj['api_key'] = @response.parsed_response['users'][0]['api_key']
-
elsif @response && @response.parsed_response && @response.parsed_response['error']
-
returnObj['error'] = @response.parsed_response['error']
-
else
-
returnObj['error'] = 'Failed to Register Account.'
-
end
-
else
-
returnObj['error'] = 'Failed to Register Account Because Current User have not SSL Account.'
-
end
-
-
render :json => returnObj
-
end
-
-
def update_resources
-
resources = params['deleted_resources']
-
is_deleted = true
-
-
if resources
-
resources.each do |resource_key|
-
@response = HTTParty.delete('https://reseller.cdnify.com/api/v1/resources/' + resource_key.split('|')[0],
-
basic_auth: {username: resource_key.split('|')[2], password: 'x'})
-
-
if @response
-
unless @response.code == 204
-
is_deleted = false
-
@response.parsed_response['errors'].each do |error|
-
flash[:error] = '' unless flash[:error]
-
flash[:error].concat("<br />") unless flash[:error] == ''
-
flash[:error].concat(resource_key.split('|')[1] + ': ' + error['code'].to_s + ': ' + error['message'])
-
end
-
end
-
else
-
flash[:error] = 'Faile to delete selected resources'
-
end
-
end
-
end
-
-
flash[:notice] = 'Successfully Updated.' if is_deleted
-
-
redirect_to cdns_path(ssl_slug: @ssl_slug)
-
end
-
-
def resource_cdn
-
@results = {}
-
@results[:bandwidth] = 0
-
@results[:hits] = 0
-
@results[:locations] = nil
-
-
if current_user.ssl_account
-
resource_id = params['id']
-
@results[:active_tab] = @tab_overview
-
@results[:active_tab] = session[:selected_tab] if session[:selected_tab]
-
session.delete(:selected_tab)
-
-
# Getting user api key for resource.
-
if current_user.is_system_admins?
-
if session[:user_api_key]
-
api_key = current_user_api_key(session[:user_api_key])
-
session.delete(:user_api_key)
-
else
-
admin_user_api_key = Rails.application.secrets.cdnify_admin_user_api_key
-
@response = HTTParty.get('https://reseller.cdnify.com/api/v1/resources/all-reseller-resources',
-
basic_auth: {username: admin_user_api_key, password: 'x'})
-
-
if @response && @response.code == 200
-
@response.parsed_response['resources'].each do |resource|
-
if resource['id'] == resource_id
-
api_key = current_user_api_key(resource['user_api_key'])
-
break
-
end
-
end
-
end
-
end
-
else
-
api_key = current_user_api_key
-
session.delete(:user_api_key) if session[:user_api_key]
-
end
-
-
if api_key
-
# Overview Data
-
@response = HTTParty.get('https://reseller.cdnify.com/api/v1/stats/' + resource_id + '/bandwidth',
-
basic_auth: {username: api_key, password: 'x'})
-
-
if @response && @response.parsed_response
-
@results[:bandwidth] = @response.parsed_response['bandwidth_usage'] &&
-
@response.parsed_response['bandwidth_usage'].length > 0 ?
-
@response.parsed_response['bandwidth_usage'][0] : 0
-
@results[:hits] = @response.parsed_response['hit_usage'] &&
-
@response.parsed_response['hit_usage'].length > 0 ?
-
@response.parsed_response['hit_usage'][0] : 0
-
@results[:locations] = @response.parsed_response['pop_usage'] &&
-
@response.parsed_response['pop_usage'].length > 0 ?
-
@response.parsed_response['pop_usage'][0] : nil
-
end
-
-
# Settings Data
-
@response = HTTParty.get('https://reseller.cdnify.com/api/v1/resources/' + resource_id,
-
basic_auth: {username: api_key, password: 'x'})
-
@results[:resource] = @response.parsed_response['resources'][0] if @response && @response.parsed_response
-
-
# Cache Data
-
@results[:expire_time] = @response.parsed_response['resources'][0]['advanced_settings']['cache_expire_time'] if @response && @response.parsed_response
-
-
@response = HTTParty.get('https://reseller.cdnify.com/api/v1/resources/' + resource_id + '/cache',
-
basic_auth: {username: api_key, password: 'x'})
-
@results[:files] = @response.parsed_response['files'] if @response && @response.parsed_response && @response.parsed_response['files']
-
else
-
flash[:error] = 'Unable to load selected resource.'
-
end
-
end
-
-
respond_to do |format|
-
format.html { render :action => "resource_cdn" }
-
format.xml { render :xml => @results }
-
end
-
end
-
-
def update_resource
-
resource_id = params[:id]
-
api_key = params[:api_key]
-
resource_origin = params[:resource_origin]
-
resource_name = params[:resource_name]
-
-
@response = HTTParty.patch('https://reseller.cdnify.com/api/v1/resources/' + resource_id,
-
{basic_auth: {username: api_key, password: 'x'}, body: {alias: resource_name, origin: resource_origin}})
-
-
if @response && @response.parsed_response
-
if @response.parsed_response['resources']
-
flash[:notice] = 'Successfully Updated General Settings.'
-
else
-
@response.parsed_response['errors'].each do |error|
-
flash[:error] = '' unless flash[:error]
-
flash[:error].concat("<br />") unless flash[:error] == ''
-
flash[:error].concat(error['code'].to_s + ': ' + error['message'])
-
end
-
end
-
else
-
flash[:error] = 'Failed to Update General Settings.'
-
end
-
-
session[:selected_tab] = @tab_setting
-
session[:user_api_key] = api_key
-
-
redirect_to resource_cdn_cdn_path(@ssl_slug, resource_id) and return
-
end
-
-
def add_custom_domain
-
resource_id = params[:id]
-
api_key = params[:api_key]
-
custom_domain = params[:custom_domain]
-
-
@response = HTTParty.post('https://reseller.cdnify.com/api/v1/resources/' + resource_id + '/custom_domains',
-
{basic_auth: {username: api_key, password: 'x'}, body: {hostname: custom_domain}})
-
-
# certificate_value = params['certificate_value']
-
# private_key = params['private_key']
-
# @response = HTTParty.post('https://reseller.cdnify.com/api/v1/resources/' + resource_id + '/custom_domains',
-
# {basic_auth: {username: api_key, password: 'x'},
-
# body: {hostname: custom_domain, certificates: {certificate: certificate_value, privateKey: private_key}}})
-
-
if @response && @response.parsed_response
-
if @response.parsed_response['errors']
-
@response.parsed_response['errors'].each do |error|
-
flash[:error] = '' unless flash[:error]
-
flash[:error].concat("<br />") unless flash[:error] == ''
-
flash[:error].concat(error['code'].to_s + ': ' + error['message'])
-
end
-
elsif @response.parsed_response['message']
-
if @response.parsed_response['id']
-
flash[:notice] = @response.parsed_response['message']
-
else
-
flash[:error] = @response.parsed_response['message']
-
end
-
end
-
else
-
flash[:error] = 'Failed to Add a New Custom Domain.'
-
end
-
-
session[:selected_tab] = @tab_setting
-
session[:user_api_key] = api_key
-
-
redirect_to resource_cdn_cdn_path(@ssl_slug, resource_id) and return
-
end
-
-
def update_custom_domain
-
resource_id = params[:id]
-
api_key = params['api_key']
-
host_name = params['host_name']
-
custom_domain_ref = params['custom_domain_ref']
-
action_type = params['action_type']
-
generate_type = params['generate_type']
-
-
if action_type == 'modify'
-
body_params = {}
-
ac = current_user.ssl_account.api_credential
-
body_params['account_key'] = ac.account_key
-
body_params['secret_key'] = ac.secret_key
-
body_params['is_test'] = true if is_sandbox?
-
body_params['ref'] = custom_domain_ref if custom_domain_ref != ''
-
-
if generate_type == 'auto'
-
@response = HTTParty.post('https://reseller.cdnify.com/api/v1/resources/' + resource_id + '/ssl_certificate/' + host_name,
-
{basic_auth: {username: api_key, password: 'x'}, body: body_params})
-
-
if @response
-
if @response.code == 200 || @response.code == 201
-
if Settings.cdn_ssl_notification_address.blank?
-
flash[:notice] = "Successfully Modified."
-
else
-
flash[:notice] = "The processing SSL certificate request has been emailed."
-
current_user.deliver_generate_install_ssl!(resource_id, host_name, Settings.cdn_ssl_notification_address)
-
end
-
else
-
flash[:error] = @response.parsed_response['error']['message']
-
end
-
else
-
flash[:error] = 'Failed to update custom domain'
-
end
-
else
-
body_params['certificate'] = params['certificate_value']
-
body_params['privateKey'] = params['private_key']
-
-
@response = HTTParty.put('https://reseller.cdnify.com/api/v1/resources/' + resource_id + '/ssl_certificate/' + host_name,
-
{basic_auth: {username: api_key, password: 'x'}, body: body_params})
-
-
if @response
-
if @response.code == 200 || @response.code == 201
-
if Settings.cdn_ssl_notification_address.blank?
-
flash[:notice] = "Successfully Modified."
-
else
-
flash[:notice] = "The processing SSL certificate request has been emailed."
-
current_user.deliver_ssl_cert_private_key!(resource_id, host_name, @response.parsed_response['id'])
-
end
-
else
-
flash[:error] = @response.parsed_response['message']
-
end
-
else
-
flash[:error] = 'Failed to update custom domain'
-
end
-
end
-
else
-
@response = HTTParty.delete('https://reseller.cdnify.com/api/v1/resources/' + resource_id + '/custom_domains/' + host_name,
-
basic_auth: {username: api_key, password: 'x'})
-
-
if @response
-
if @response.parsed_response
-
if @response.parsed_response['errors']
-
@response.parsed_response['errors'].each do |error|
-
flash[:error] = '' unless flash[:error]
-
flash[:error].concat("<br />") unless flash[:error] == ''
-
flash[:error].concat(error['code'].to_s + ': ' + error['message'])
-
end
-
end
-
else
-
flash[:notice] = 'Successfully Deleted.'
-
end
-
else
-
flash[:error] = 'Failed to delete custom domain'
-
end
-
end
-
-
session[:selected_tab] = @tab_setting
-
session[:user_api_key] = api_key
-
-
redirect_to resource_cdn_cdn_path(@ssl_slug, resource_id) and return
-
end
-
-
def update_advanced_setting
-
resource_id = params[:id]
-
api_key = params[:api_key]
-
-
@response = HTTParty.patch('https://reseller.cdnify.com/api/v1/resources/' + resource_id + '/settings',
-
{basic_auth: {username: api_key, password: 'x'}, body: {
-
allow_robots: !params[:allow_robots].blank?,
-
cache_query_string: !params[:cache_query_string].blank?,
-
enable_cors: !params[:enable_cors].blank?,
-
disable_gzip: !params[:disable_gzip].blank?,
-
force_ssl: !params[:pull_https].blank?,
-
pull_https: !params[:pull_https].blank?,
-
link: !params[:link].blank?
-
}})
-
-
if @response && @response.parsed_response
-
if @response.parsed_response['resource']
-
flash[:notice] = 'Successfully Updated Advanced Settings.'
-
else
-
@response.parsed_response['errors'].each do |error|
-
flash[:error] = '' unless flash[:error]
-
flash[:error].concat("<br />") unless flash[:error] == ''
-
flash[:error].concat(error['code'].to_s + ': ' + error['message'])
-
end
-
end
-
else
-
flash[:error] = 'Failed to Update Advanced Settings.'
-
end
-
-
session[:selected_tab] = @tab_setting
-
session[:user_api_key] = api_key
-
-
redirect_to resource_cdn_cdn_path(@ssl_slug, resource_id) and return
-
end
-
-
def check_cname
-
resource_name = params['resource_name'] + '.a.cdnify.io'
-
custom_domain = params['custom_domain']
-
-
exist = begin
-
Timeout.timeout(Surl::TIMEOUT_DURATION) do
-
txt = Resolv::DNS.open do |dns|
-
records = dns.getresources(custom_domain, Resolv::DNS::Resource::IN::CNAME)
-
end
-
resource_name == txt.last.name.to_s
-
end
-
rescue Exception=>e
-
false
-
end
-
-
render :json => exist
-
end
-
-
def delete_resource
-
resource_id = params[:id]
-
api_key = params[:api_key]
-
-
@response = HTTParty.delete('https://reseller.cdnify.com/api/v1/resources/' + resource_id,
-
basic_auth: {username: api_key, password: 'x'})
-
-
if @response
-
if @response.parsed_response
-
@response.parsed_response['errors'].each do |error|
-
flash[:error] = '' unless flash[:error]
-
flash[:error].concat("<br />") unless flash[:error] == ''
-
flash[:error].concat(error['code'].to_s + ': ' + error['message'])
-
end
-
-
session[:selected_tab] = @tab_setting
-
-
redirect_to resource_cdn_cdn_path(@ssl_slug, resource_id) and return
-
else
-
flash[:notice] = 'Successfully Deleted Resource.'
-
end
-
else
-
flash[:error] = 'Failed to delete resource.'
-
end
-
-
redirect_to cdns_path(ssl_slug: @ssl_slug)
-
end
-
-
def purge_cache
-
resource_id = params[:id]
-
api_key = params[:api_key]
-
files = params[:purge_files].split(',')
-
is_purge_all = params[:purge_all]
-
-
if is_purge_all == 'true'
-
@response = HTTParty.delete('https://reseller.cdnify.com/api/v1/resources/' + resource_id + '/cache',
-
basic_auth: {username: api_key, password: 'x'})
-
else
-
@response = HTTParty.delete('https://reseller.cdnify.com/api/v1/resources/' + resource_id + '/cache',
-
{basic_auth: {username: api_key, password: 'x'}, body: {files: files}})
-
end
-
-
if @response
-
if @response.parsed_response
-
@response.parsed_response['errors'].each do |error|
-
flash[:error] = '' unless flash[:error]
-
flash[:error].concat("<br />") unless flash[:error] == ''
-
flash[:error].concat(error['code'].to_s + ': ' + error['message'])
-
end
-
else
-
flash[:notice] = 'Successfully Purged File(s).'
-
end
-
else
-
flash[:error] = 'Failed to purge file(s).'
-
end
-
-
session[:selected_tab] = @tab_cache
-
session[:user_api_key] = api_key
-
-
redirect_to resource_cdn_cdn_path(@ssl_slug, resource_id) and return
-
end
-
-
def update_cache_expiry
-
resource_id = params[:id]
-
api_key = params[:api_key]
-
-
@response = HTTParty.patch('https://reseller.cdnify.com/api/v1/resources/' + resource_id + '/settings',
-
{basic_auth: {username: api_key, password: 'x'}, body: {cache_expire_time: params[:expiry_hours]}})
-
-
if @response && @response.parsed_response
-
if @response.parsed_response['resource']
-
flash[:notice] = 'Successfully Updated Cache Expire Time.'
-
else
-
@response.parsed_response['errors'].each do |error|
-
flash[:error] = '' unless flash[:error]
-
flash[:error].concat("<br />") unless flash[:error] == ''
-
flash[:error].concat(error['code'].to_s + ': ' + error['message'])
-
end
-
end
-
else
-
flash[:error] = 'Failed to Update Cache Expire Time.'
-
end
-
-
session[:selected_tab] = @tab_cache
-
session[:user_api_key] = api_key
-
-
redirect_to resource_cdn_cdn_path(@ssl_slug, resource_id) and return
-
end
-
-
# GET /cdns/1
-
# GET /cdns/1.json
-
def show
-
render json: @cdn
-
end
-
-
# POST /cdns
-
# POST /cdns.json
-
def create
-
api_key = params[:api_key]
-
resource_name = params[:resource_name]
-
resource_origin = params[:resource_origin]
-
-
@response = HTTParty.post('https://reseller.cdnify.com/api/v1/resources',
-
{basic_auth: {username: api_key, password: 'x'}, body: {alias: resource_name, origin: resource_origin}})
-
-
if @response && @response.parsed_response
-
if @response.parsed_response['resources']
-
flash[:notice] = 'Successfully Created Resource.'
-
else
-
@response.parsed_response['errors'].each do |error|
-
flash[:error] = '' unless flash[:error]
-
flash[:error].concat("<br />") unless flash[:error] == ''
-
flash[:error].concat(error['code'].to_s + ': ' + error['message'])
-
end
-
end
-
else
-
flash[:error] = 'Failed to Create Resource.'
-
end
-
-
redirect_to cdns_path(ssl_slug: @ssl_slug)
-
end
-
-
# PATCH/PUT /cdns/1
-
# PATCH/PUT /cdns/1.json
-
def update
-
if @cdn.update(cdn_params)
-
head :no_content
-
else
-
render json: @cdn.errors, status: :unprocessable_entity
-
end
-
end
-
-
# DELETE /cdns/1
-
# DELETE /cdns/1.json
-
def destroy
-
@cdn.destroy
-
-
head :no_content
-
end
-
-
private
-
-
def set_row_page
-
preferred_row_count = current_user.preferred_cdn_row_count
-
@per_page = params[:per_page] || preferred_row_count.or_else("10")
-
Cdn.per_page = @per_page if Cdn.per_page != @per_page
-
-
if @per_page != preferred_row_count
-
current_user.preferred_cdn_row_count = @per_page
-
current_user.save(validate: false)
-
end
-
-
@p = {page: (params[:page] || 1), per_page: @per_page}
-
end
-
-
def set_cdn
-
@cdn = (current_user.is_system_admins? ? Cdn : current_user.ssl_account.cdns).find(params[:id])
-
end
-
-
def set_tab_name
-
@tab_overview = 'overview'
-
@tab_cache = 'caches'
-
@tab_setting = 'settings'
-
end
-
-
def cdn_params
-
params.require(:cdn).permit()
-
end
-
-
def current_user_api_key(key = nil)
-
return @current_user_api_key if defined?(@current_user_api_key)
-
-
if key
-
@current_user_api_key = key
-
else
-
if current_user.is_system_admins?
-
@current_user_api_key = Rails.application.secrets.cdnify_admin_user_api_key
-
else
-
email_addr = current_user.ssl_account.acct_number + '@ssl.com'
-
email_addr = 'sandbox-' + email_addr if is_sandbox?
-
reseller_api_key = Rails.application.secrets.cdnify_reseller_api_key
-
-
@response = HTTParty.get('https://reseller.cdnify.com/users/' + email_addr + '?email=True',
-
basic_auth: {username: reseller_api_key, password: 'x'})
-
-
@current_user_api_key = @response && @response.code == 200 ? @response.parsed_response['users'][0]['api_key'] : nil
-
end
-
end
-
end
-
end
-
class CertificateContentsController < ApplicationController
-
layout 'application'
-
-
filter_access_to :update_tags
-
-
def show
-
redirect_to certificate_order_path(@ssl_slug, CertificateContent.find(params[:id]).certificate_order)
-
end
-
-
# PUT /contacts/1
-
# PUT /contacts/1.xml
-
def update
-
@certificate_content = CertificateContent.find(params[:id])
-
@certificate_order = @certificate_content.certificate_order
-
unless params[:certificate_content].nil?
-
@contacts_attributes = params[:certificate_content][:certificate_contacts_attributes]
-
end
-
-
if Contact.optional_contacts? && optional_contacts_params?(params)
-
add_saved_contact(params) if params[:add_saved_contact]
-
remove_select_contact(params) if params[:remove_selected_contact]
-
create_contact(params) if params[:create_contact]
-
update_selected_contact(params) if params[:update_selected_contact]
-
update_available_contact(params) if params[:update_available_contact]
-
update_role(params) if params[:update_role]
-
else
-
respond_to do |format|
-
proceed = if (has_all_contacts? && !params[:certificate_content])
-
true
-
elsif !has_all_contacts? && !params[:certificate_content]
-
false
-
else
-
updated = @certificate_content.update_attributes(
-
params[:certificate_content].except(:certificate_contacts_attributes)
-
)
-
create_contacts_required(params) if updated
-
-
updated && has_all_contacts?
-
end
-
-
if proceed
-
if @certificate_content.info_provided?
-
@certificate_content.provide_contacts!
-
format.html { redirect_to new_certificate_order_validation_path(
-
@ssl_slug, @certificate_content.certificate_order)
-
}
-
else
-
flash[:notice] = 'Contacts were successfully updated.'
-
format.html { redirect_to certificate_order_path(@ssl_slug, @certificate_content.certificate_order) }
-
format.xml { head :ok }
-
end
-
else
-
if !has_all_contacts? && Contact.optional_contacts?
-
flash[:error] = 'Requires at least one contact for this certificate.'
-
else
-
error = if @certificate_content.certificate_order.errors.any?
-
@certificate_content.certificate_order.errors
-
else
-
missing_roles = %w(administrative billing technical validation) - @certificate_content.certificate_contacts.map(&:roles).flatten.uniq
-
"Missing information for roles: #{missing_roles.join(', ')}." if missing_roles.count > 0
-
end
-
flash[:error] = error
-
end
-
@saved_contacts = current_user.ssl_account.saved_contacts
-
format.html { render :file => "/contacts/index", :layout=> 'application'}
-
format.xml { render :xml =>
-
@certificate_content.certificate_order.errors,
-
:status => :unprocessable_entity }
-
end
-
end
-
end
-
end
-
-
def update_tags
-
@cc = CertificateContent.find params[:id]
-
if @cc
-
@taggable = @cc
-
Tag.update_for_model(@taggable, params[:tags_list])
-
end
-
render json: {
-
tags_list: @taggable.nil? ? [] : @taggable.tags.pluck(:name)
-
}
-
end
-
-
private
-
#
-
# Optional contacts ENABLED
-
# ============================================================================
-
def optional_contacts_params?(params)
-
result = false
-
list = %w(
-
add_saved_contact
-
remove_selected_contact
-
create_contact
-
update_selected_contact
-
update_available_contact
-
update_role
-
)
-
list.each { |param| result = true if params.include?(param) }
-
result
-
end
-
-
def update_role(params)
-
contact = find_contact_from_team params[:update_role_id]
-
if contact
-
cur_roles = contact.roles
-
admin_role = ['administrative']
-
new_role = params[:update_role]
-
contact.roles = if params[:update_role_checked]=='false' # role unchecked
-
cur_roles - [new_role]
-
else # role checked
-
new_role == 'administrative' ? admin_role : (cur_roles + [new_role] - admin_role)
-
end
-
contact.save
-
end
-
render_contacts
-
end
-
-
def add_saved_contact(params)
-
parent_id = params[:add_saved_contact].to_i
-
saved_contact = Contact.find parent_id
-
already_exists = @certificate_content.certificate_contacts.where(parent_id: parent_id).any?
-
-
if saved_contact && !already_exists
-
roles = (saved_contact.roles.is_a?(String) || saved_contact.roles.blank?) ? [] : saved_contact.roles
-
@certificate_content.certificate_contacts.create(
-
saved_contact.attributes
-
.keep_if {|k,_| (Contact::SYNC_FIELDS - [:roles]).include? k.to_sym}
-
.merge(parent_id: parent_id, roles: roles)
-
)
-
end
-
render_contacts
-
end
-
-
def remove_select_contact(params)
-
remove = @certificate_content.certificate_contacts
-
.find_by(id: params[:remove_selected_contact].to_i)
-
if remove && remove.parent_id
-
contacts = @certificate_content.certificate_contacts
-
.where(parent_id: remove.parent_id)
-
contacts.destroy_all
-
NotificationGroup.auto_manage_email_address(@certificate_content, 'delete', contacts)
-
else
-
remove.destroy if remove
-
NotificationGroup.auto_manage_email_address(@certificate_content, 'delete', [remove])
-
end
-
render_contacts
-
end
-
-
def create_contact(params)
-
contact = params[:contact]
-
parent_id = nil
-
errors = nil
-
attrs = contact.except(*CertificateOrder::ID_AND_TIMESTAMP).except(:save_for_later)
-
-
if contact[:save_for_later]=='1' # create saved contact?
-
saved = @certificate_content.ssl_account.saved_contacts.create(attrs)
-
errors = saved.errors unless saved.valid?
-
parent_id = saved.id if saved.valid?
-
end
-
-
if errors.nil?
-
saved = @certificate_content.certificate_contacts
-
.create(attrs.merge(parent_id: parent_id))
-
errors = saved.errors unless saved.valid?
-
end
-
-
if errors.blank?
-
render_contacts
-
else
-
render json: errors.messages, status: :unprocessable_entity
-
end
-
end
-
-
def update_selected_contact(params)
-
parent_id = nil
-
errors = nil
-
attrs = params[:contact].except(*CertificateOrder::ID_AND_TIMESTAMP)
-
.except(:save_for_later).merge(roles: [params[:contact][:roles]])
-
-
if params[:contact][:save_for_later]=='1' # create saved contact?
-
saved = @certificate_content.ssl_account.saved_contacts
-
.create(attrs.except(:roles))
-
errors = saved.errors unless saved.valid?
-
parent_id = saved.id if saved.valid?
-
end
-
-
if errors.nil?
-
found = CertificateContact.find_by(id: params[:contact][:id].to_i)
-
found.assign_attributes(attrs.merge(parent_id: parent_id))
-
errors = found.errors unless found.valid?
-
if found.changed? && errors.nil?
-
found.save
-
NotificationGroup.auto_manage_email_address(@certificate_content, 'update', [found])
-
end
-
end
-
if errors.blank?
-
render_contacts
-
else
-
render json: errors.messages, status: :unprocessable_entity
-
end
-
end
-
-
def update_available_contact(params)
-
contact = Contact.find_by(id: params[:contact][:id].to_i)
-
if contact.update_attributes(params[:contact])
-
NotificationGroup.auto_manage_email_address(@certificate_content, 'update', [contact])
-
render_contacts
-
else
-
render json: contact.errors.messages, status: :unprocessable_entity
-
end
-
end
-
-
def render_contacts
-
partial = render_to_string(partial: '/contacts/index_optional', layout: false)
-
render json: {content: partial}, status: :ok
-
end
-
-
#
-
# Optional contacts DISABLED
-
# ============================================================================
-
def create_contacts_required(params)
-
CertificateContent::CONTACT_ROLES.each_with_index do |role, index|
-
@current_attributes = @contacts_attributes[index.to_s]
-
@saved_contact = update_saved_contact(@current_attributes) # saved contact
-
@existing_contact = @certificate_content.send("#{role}_contact")
-
-
if @existing_contact.blank?
-
create_certificate_contact
-
else
-
update_certificate_contact
-
end
-
end
-
end
-
-
def create_certificate_contact
-
attrs = if @saved_contact
-
@saved_contact.attributes
-
.keep_if {|k,_| Contact::SYNC_FIELDS_REQUIRED.include? k.to_sym}
-
.merge(parent_id: @current_attributes[:parent_id])
-
.merge(roles: @current_attributes[:roles])
-
else
-
@current_attributes
-
end
-
@certificate_content.certificate_contacts.create(
-
attrs.except(*CertificateOrder::ID_AND_TIMESTAMP)
-
)
-
end
-
-
def update_certificate_contact
-
attrs = if @saved_contact
-
@saved_contact.attributes
-
.keep_if {|k,_| Contact::SYNC_FIELDS_REQUIRED.include? k.to_sym}
-
.merge(parent_id: @current_attributes[:parent_id])
-
.merge(roles: @current_attributes[:roles])
-
else
-
@current_attributes
-
end
-
-
@existing_contact.assign_attributes(attrs)
-
if @existing_contact.changed?
-
@existing_contact.save
-
end
-
end
-
-
def update_saved_contact(params)
-
cc = nil
-
unless !params || params[:parent_id].blank?
-
cc = CertificateContact.find_by(id: params[:parent_id])
-
if cc && !params[:update_parent].blank?
-
cc.assign_attributes(params.permit(Contact::SYNC_FIELDS_REQUIRED))
-
cc.save if cc.changed?
-
end
-
end
-
cc
-
end
-
-
def has_all_contacts?
-
@certificate_content.has_all_contacts?
-
end
-
-
def find_contact_from_team(target_id)
-
found = @certificate_content.certificate_contacts.find_by(id: target_id.to_i)
-
found = @certificate_content.ssl_account.saved_contacts.find_by(id: found.parent_id) if found && found.parent_id
-
found = @certificate_content.ssl_account.saved_contacts.find_by(id: target_id.to_i) if !found && target_id
-
found
-
end
-
end
-
class CertificateEnrollmentRequestsController < ApplicationController
-
include OrdersHelper
-
before_action :require_user, except: [:new, :create, :enrollment_links]
-
before_action :find_request, only: [:reject, :destroy]
-
before_action :find_ssl_account, only: [:new, :create, :enrollment_links]
-
filter_access_to :all, except: [:new, :create, :enrollment_links]
-
-
def index
-
@requests = requests_base_query.joins(:certificate).sort_with(params)
-
@requests = @requests.index_filter(params) if params[:commit]
-
@requests = @requests.paginate(page: params[:page], per_page: 25)
-
end
-
-
def enrollment_links
-
@certificates = Certificate.order(title: :asc).available.base_products
-
end
-
-
def new
-
setup_request
-
end
-
-
def find_certificate
-
find_by = if params[:product]
-
{ product: params[:product] }
-
else
-
{ id: (params[:certificate_id] || params[:certificate_enrollment_request][:certificate_id]) }
-
end
-
@certificate = Certificate.find_by(find_by)
-
end
-
-
def create
-
cer = params[:certificate_enrollment_request]
-
@request = setup_request_create
-
-
if @request.save
-
team = @request.ssl_account
-
(team.get_account_admins << team.get_account_owner).each do |team_admin|
-
OrderNotifier.enrollment_request_for_team(team, @request, team_admin).deliver
-
end
-
-
target_path = if current_user && (current_user.is_owner? || current_user.is_account_admin?)
-
certificate_enrollment_requests_path(cer[:ssl_slug])
-
else
-
enrollment_links_certificate_enrollment_requests_path(cer[:ssl_slug])
-
end
-
-
redirect_to target_path,
-
notice: "Enrollment Request was successfully created."
-
else
-
render :new,
-
error: "Failed to enroll due to errors, #{@request.errors.full_messages.join(', ')}."
-
end
-
end
-
-
def reject
-
@request.rejected!
-
redirect_to :back, notice: "Enrollment Request was successfully rejected."
-
end
-
-
def destroy
-
if @request and @request.destroy
-
flash[:notice] = "Enrollment Request was successfully deleted."
-
end
-
redirect_to certificate_enrollment_requests_path(@ssl_slug)
-
end
-
-
private
-
-
def setup_request
-
find_certificate
-
@ssl_slug = params[:ssl_slug]
-
@duration = (params[:duration].to_i/365).to_i
-
@request = CertificateEnrollmentRequest.new
-
-
unless @certificate.blank?
-
@certificate_order = CertificateOrder.new(
-
duration: @duration,
-
ssl_account: @ssl_account,
-
has_csr: false
-
)
-
@certificate_content = CertificateContent.new(domains: [])
-
end
-
end
-
-
def setup_request_create
-
find_certificate
-
cer = params[:certificate_enrollment_request]
-
-
domains = cer[:signing_request] ? sslcom_request_domains : smime_client_parse_emails(cer[:domains])
-
-
@request = CertificateEnrollmentRequest.new(
-
domains: domains,
-
certificate_id: cer[:certificate_id],
-
ssl_account_id: @ssl_account.try(:id),
-
duration: cer[:duration],
-
server_software_id: cer[:server_software_id],
-
signing_request: cer[:signing_request],
-
status: CertificateEnrollmentRequest.statuses[:pending],
-
)
-
end
-
-
def sslcom_request_domains
-
cer = params[:certificate_enrollment_request]
-
domains = [cer[:common_name].downcase]
-
additional_domains = cer[:additional_domains]
-
-
if additional_domains && !additional_domains.strip.blank?
-
domains << additional_domains.strip.split(/[\s,]+/).map(&:strip).map(&:downcase)
-
end
-
domains.uniq
-
end
-
-
def find_ssl_account_by_slug
-
@ssl_account = SslAccount.find_by(
-
ssl_slug: ( params[:ssl_slug] || params[:certificate_enrollment_request][:ssl_slug] )
-
)
-
end
-
-
def find_request
-
@request = requests_base_query.find(params[:id])
-
end
-
-
def requests_base_query
-
base = if current_user.is_system_admins?
-
CertificateEnrollmentRequest.all
-
else
-
current_user.ssl_account.certificate_enrollment_requests
-
end
-
end
-
end
-
class CertificateOrderSweeper < ActionController::Caching::Sweeper
-
observe CertificateOrder # This sweeper is going to keep an eye on the CertificateOrder model
-
-
# If our sweeper detects that a CertificateOrder was created call this
-
def after_create(certificate_order)
-
expire_cache_for(certificate_order)
-
end
-
-
# If our sweeper detects that a CertificateOrder was updated call this
-
def after_update(certificate_order)
-
expire_cache_for(certificate_order)
-
end
-
-
# If our sweeper detects that a CertificateOrder was deleted call this
-
def after_destroy(certificate_order)
-
expire_cache_for(certificate_order)
-
end
-
-
private
-
-
def expire_cache_for(certificate_order)
-
expire_fragment('admin_header_certs_status')
-
end
-
end
-
class CertificateOrderTokensController < ApplicationController
-
before_action :require_user, only: [:confirm]
-
before_action :find_ssl_account, only: [:confirm]
-
-
def create
-
respond_to do |format|
-
returnObj = {}
-
-
if current_user
-
team_account =
-
if params[:ssl_slug]
-
(current_user.is_system_admins? ? SslAccount : current_user.ssl_accounts).find_by_acct_number(params[:ssl_slug]) ||
-
(current_user.is_system_admins? ? SslAccount : current_user.ssl_accounts).find_by_ssl_slug(params[:ssl_slug])
-
else
-
current_user.ssl_account
-
end
-
if team_account.blank?
-
returnObj['status'] = 'not_found_ssl_account'
-
else
-
co = current_user.certificate_order_by_ref(params[:certificate_order_ref])
-
-
# Finding and Setting Assignee to Certificate Order
-
# and assign individual_certificate role to assignee in scope of the team.
-
email_address = co.get_download_cert_email
-
assignee = User.find_by_email(email_address)
-
-
unless co.certificate.is_smime_or_client?
-
co.update_attribute(:assignee, assignee) unless co.assignee == assignee
-
-
if assignee && !assignee.duplicate_role?(Role.get_individual_certificate_id, co.ssl_account)
-
assignee.ssl_accounts << co.ssl_account
-
assignee.ssl_account_users.where(ssl_account_id: co.ssl_account.id).first.update_attribute(:approved, true)
-
assignee.set_roles_for_account(co.ssl_account, [Role.get_individual_certificate_id])
-
end
-
end
-
-
# create / update certificate order token table
-
# co_token = co.certificate_order_tokens.where(status: nil, is_expired: false).last
-
co_token = co.generate_certificate_order_token
-
if co_token && !co_token.is_expired
-
co_token.update_attributes(due_date: 7.days.from_now, user: assignee)
-
else
-
co_token = CertificateOrderToken.new
-
co_token.certificate_order = co
-
co_token.ssl_account = team_account
-
co_token.user = assignee
-
co_token.is_expired = false
-
co_token.due_date = 7.days.from_now
-
co_token.token = (SecureRandom.hex(8)+Time.now.to_i.to_s(32))[0..19]
-
co_token.save!
-
end
-
-
if params['send_email_link'].blank? || (!params['send_email_link'].blank? && params['send_email_link'] == 'true')
-
# Notifying to assignee
-
OrderNotifier.certificate_order_token_send(co, co_token.token).deliver
-
returnObj['send_email'] = 'true'
-
else
-
returnObj['send_email'] = 'false'
-
end
-
-
if !params['copy_act_link'].blank? && (params['copy_act_link'] == 'true')
-
returnObj['act_link'] = confirm_url(co_token.token)
-
else
-
returnObj['act_link'] = 'false'
-
end
-
-
co.certificate_content.validate! if co.certificate_content.issued?
-
-
returnObj['status'] = 'success'
-
end
-
else
-
returnObj['status'] = 'session_expired'
-
end
-
-
# format.js { render :json => returnObj['status'].to_json }
-
format.js { render :json => returnObj.to_json }
-
end
-
end
-
-
def request_token
-
respond_to do |format|
-
returnObj = {}
-
-
if current_user
-
co = current_user.certificate_order_by_ref(params[:certificate_order_ref])
-
co.update_attribute(:request_status, 'done')
-
-
# Sending Notify to SysAdmin role's users.
-
sys_admins = User.search_sys_admin.uniq
-
sys_admins.each do |sys_admin|
-
OrderNotifier.request_token_send(co, sys_admin, current_user).deliver
-
end
-
-
# Sending Notify to TeamAdmin role's users.
-
team_account = current_user.ssl_account
-
unless team_account.blank?
-
team_admins = team_account.get_account_admins
-
team_admins.each do |team_admin|
-
OrderNotifier.request_token_send(co, team_admin, current_user).deliver
-
end
-
end
-
-
returnObj['status'] = 'success'
-
else
-
returnObj['status'] = 'session_expired'
-
end
-
-
format.js { render :json => returnObj.to_json }
-
end
-
end
-
-
def confirm
-
co_token = CertificateOrderToken.find_by_token(params[:token])
-
if co_token.user.blank? and co_token.certificate_order.get_download_cert_email==current_user.email
-
co_token.update_column :user_id, current_user.id
-
end
-
-
if co_token
-
if co_token.is_expired
-
flash[:error] = "The page has expired or is no longer valid"
-
elsif co_token.due_date < DateTime.now
-
flash[:error] = "The page has expired or is no longer valid"
-
co_token.update_attribute(:is_expired, true)
-
elsif co_token.user != current_user or co_token.certificate_order.get_download_cert_email!=current_user.email
-
flash[:error] = "Access to this page is denied. Please log in as the user assigned this token."
-
else
-
ssl_slug = co_token.certificate_order.ssl_account.acct_number || co_token.certificate_order.ssl_account.ssl_slug
-
redirect_to generate_cert_certificate_order_path(ssl_slug, co_token.certificate_order.ref) and return
-
end
-
else
-
flash[:error] = "Provided URL is incorrect."
-
end
-
end
-
end
-
#ordering a certificate can be convoluted process because we wanted to maximize seo in the url and not
-
#necessarily follow proper REST. the flow is as follows:
-
#CertificatesController#buy
-
#OrdersController#new
-
#(or CertificateOrdersController#update_csr if unused credit)
-
#FundedAccount#allocate_funds or #confirm_funds if from funded_account (ie reseller)
-
#OrdersController#create_multi_free_ssl or OrdersController#create_free_ssl
-
#CertificateOrdersController#edit (goes to application info prompt) or OrdersController#edit or OrdersController#new
-
#CertificateOrdersController#update (goes to provide contacts prompt)
-
#CertificateContentsController#update if not express
-
#ValidationsController#new (asks for validation dcv and docs if not intranet/ucc, otherwise completes order)
-
#ValidationsController#upload
-
#
-
#order is sent to api in the pend_validation workflow transition in certificate_content
-
#OrderNotifier views contain all the email sent to customer during order
-
-
class CertificateOrdersController < ApplicationController
-
layout 'application'
-
include OrdersHelper
-
include CertificateOrdersHelper
-
-
skip_before_action :verify_authenticity_token, only: [:parse_csr]
-
filter_access_to :all, except: [:generate_cert]
-
filter_access_to :read, :update, :delete, :show, :edit, :developer, :recipient
-
filter_access_to :incomplete, :pending, :search, :reprocessing, :order_by_csr, :require=>:read
-
filter_access_to :credits, :filter_by, :filter_by_scope, :require=>:index
-
filter_access_to :update_csr, :generate_cert, require: [:update]
-
filter_access_to :download, :start_over, :reprocess, :admin_update, :change_ext_order_number, :switch_from_comodo,
-
:developers, :require=>[:update, :delete]
-
filter_access_to :renew, :parse_csr, require: [:create]
-
filter_access_to :auto_renew, require: [:admin_manage]
-
filter_access_to :show_cert_order, :validate_issue, :register_domains, :require=>:ajax
-
before_filter :find_certificate, only: [:enrollment]
-
before_filter :load_certificate_order,
-
only: [:show, :show_cert_order, :validate_issue, :update, :edit, :download, :destroy, :delete, :update_csr, :auto_renew, :start_over,
-
:change_ext_order_number, :admin_update, :developer, :sslcom_ca, :update_tags, :recipient, :validate_issue]
-
before_filter :set_row_page, only: [:index, :search, :credits, :pending, :filter_by_scope, :order_by_csr, :filter_by,
-
:incomplete, :reprocessing]
-
before_filter :get_team_tags, only: [:index, :search]
-
before_filter :construct_special_fields, only: [:edit, :create, :update, :update_csr]
-
in_place_edit_for :certificate_order, :notes
-
in_place_edit_for :csr, :signed_certificate_by_text
-
-
before_action :set_schedule_value, only: [:edit, :reprocess]
-
before_action :set_algorithm_and_size, only: [:generate_cert]
-
-
NUM_ROWS_LIMIT=2
-
-
def smime_client_enrollment
-
if params[:get_duration]
-
render_certificate_durations
-
elsif params[:smime_client_create]
-
smime_client_create
-
else
-
smime_client_init
-
end
-
end
-
-
def update_tags
-
if @certificate_order
-
@taggable = @certificate_order
-
get_team_tags
-
Tag.update_for_model(@taggable, params[:tags_list])
-
end
-
render json: {
-
tags_list: @taggable.nil? ? [] : @taggable.tags.pluck(:name)
-
}
-
end
-
-
def generate_cert
-
co_token = CertificateOrderToken.find_by_token(params[:token])
-
if co_token.user.blank? and co_token.certificate_order.get_download_cert_email==current_user.try(:email) and
-
Settings.require_login_smime_claim==true
-
co_token.update_column :user_id, current_user.id
-
end
-
is_expired = false
-
-
if co_token
-
if co_token.user != current_user and Settings.require_login_smime_claim==true
-
is_expired = true
-
flash[:error] = "Access to this page is denied. Please log in as the user assigned to this token."
-
elsif co_token.is_expired
-
is_expired = true
-
flash[:error] = "The page has expired or is no longer valid."
-
# elsif co_token.due_date < DateTime.now
-
# is_expired = true
-
# # co_token.update_attribute(:is_expired, true)
-
#
-
# flash[:error] = "The page has expired or is no longer valid."
-
else
-
@certificate_order = co_token.certificate_order
-
@token = params[:token]
-
@managed_csr = Csr.find_by_ref(params[:csr_ref]) unless params[:csr_ref].blank?
-
end
-
else
-
is_expired = true
-
flash[:error] = "Provided token is incorrect."
-
end
-
-
if is_expired
-
render "confirm"
-
else
-
render "generate_cert"
-
end
-
end
-
-
def show_cert_order
-
if current_user
-
render :partial=>'detailed_info', :locals=>{:certificate_order=>@certificate_order}
-
else
-
render :json => 'no-user'
-
end
-
end
-
-
def search
-
index
-
end
-
-
# GET /certificate_orders
-
# GET /certificate_orders.xml
-
def index
-
-
@certificate_orders = find_certificate_orders.paginate(@p)
-
-
respond_to do |format|
-
format.html { render :action => :index }
-
format.xml { render :xml => @certificate_orders }
-
end
-
end
-
-
# GET /certificate_orders/1
-
# GET /certificate_orders/1.xml
-
def show
-
if @certificate_order.workflow_state=="refunded"
-
not_found
-
else
-
@taggable = @certificate_order
-
get_team_tags
-
redirect_to edit_certificate_order_path(@ssl_slug, @certificate_order) and return if @certificate_order.certificate_content && @certificate_order.certificate_content.new?
-
respond_to do |format|
-
format.html # show.html.erb
-
format.xml { render :xml => @certificate_order }
-
end
-
end
-
end
-
-
def validate_issue
-
cc = @certificate_order.certificate_content
-
@certificate_order.apply_for_certificate(
-
mapping: cc.ca,
-
current_user: current_user
-
)
-
render :json => cc.issued?
-
end
-
-
def auto_renew
-
action = CertificateOrder::RENEWING
-
iv = recert(action)
-
unless iv.blank?
-
redirect_to buy_certificate_url(iv.renewal_certificate,
-
{action.to_sym=>params[:id]})
-
else
-
not_found
-
end
-
end
-
-
def sslcom_ca
-
-
end
-
-
def renew
-
action = CertificateOrder::RENEWING
-
iv = recert(action)
-
unless iv.blank?
-
redirect_to buy_renewal_certificate_url(iv.renewal_certificate,
-
{action.to_sym=>params[:id]})
-
else
-
not_found
-
end
-
end
-
-
# GET /certificate_orders/1/edit
-
-
def edit
-
unless @certificate_order.blank?
-
if @certificate_order.certificate_content.ca.blank?
-
cc=@certificate_order.certificate_content
-
cc.add_ca(@certificate_order.ssl_account) if @certificate_order.external_order_number.blank?
-
cc.save
-
end
-
if (@certificate_order.certificate.is_client_pro? || @certificate_order.certificate.is_client_basic?) &&
-
!@certificate_order.certificate_content.validated?
-
redirect_to recipient_certificate_order_path(@ssl_slug, @certificate_order.ref)
-
else
-
@certificate = @certificate_order.mapped_certificate
-
-
unless @certificate.admin_submit_csr?
-
-
if @certificate_order.is_unused_credit?
-
@certificate_order.has_csr=true
-
@certificate_content = @certificate_order.certificate_content
-
@certificate_content.agreement=true
-
-
@notification_groups = @certificate_order.ssl_account.notification_groups.pluck(:friendly_name, :ref)
-
@notification_groups.insert(0, ['none', 'none']) if @notification_groups.empty?
-
-
@managed_csrs = (@certificate_order.ssl_account.all_csrs)
-
.sort_by{|arr| arr.try(:common_name) || ""}
-
.map{|arr| [(arr.friendly_name || arr.try(:common_name) || "")+' '+ arr.public_key_sha1,
-
arr.ref]}
-
.delete_if{|arr| arr.second == nil}
-
@managed_csrs.insert(0, ['none', 'none'])
-
-
if params[:csr_ref]
-
@generated_csr = params[:csr_ref]
-
end
-
-
@is_reprocess = false
-
-
return render '/certificates/buy', :layout=>'application'
-
end
-
unless @certificate_order.certificate_content.csr_submitted? or params[:registrant]
-
redirect_to certificate_order_path(@ssl_slug, @certificate_order)
-
else
-
@csr = @certificate_order.certificate_content.csr
-
registrants_on_edit
-
end
-
else
-
registrants_on_edit
-
end
-
@saved_registrants = @certificate_order.ssl_account.saved_registrants
-
end
-
-
unless params[:approve_phone].blank?
-
flash[:notice] = "It needs to verify phone number."
-
end
-
else
-
not_found
-
end
-
end
-
-
# GET /certificate_orders/1/reprocess
-
def reprocess
-
@certificate_order = recert(CertificateOrder::REPROCESSING)
-
@certificate_order.unchain_comodo if @certificate_order.signed_certificate_duration_delta > 1
-
@tier = find_tier
-
unless @certificate_order.blank?
-
if @certificate_order.certificate_content.workflow_state == 'pending_validation' &&
-
!current_user.is_system_admins?
-
redirect_to new_certificate_order_validation_path(@ssl_slug, @certificate_order)
-
else
-
@certificate_order.has_csr=true
-
@certificate = @certificate_order.mapped_certificate
-
@certificate_content = @certificate_order.certificate_contents.build(
-
domains: @certificate_order.certificate_content.signed_certificate.try(:subject_alternative_names),
-
server_software_id: @certificate_order.certificate_content.server_software_id
-
)
-
# @certificate_content.additional_domains = domains
-
#reset dcv validation
-
@certificate_content.add_ca(@certificate_order.ssl_account) if @certificate_order.external_order_number.blank?
-
@certificate_content.agreement=true
-
@certificate_order.validation.validation_rules.each do |vr|
-
if vr.description=~/\Adomain/
-
ruling=@certificate_order.validation.validation_rulings.detect{|vrl| vrl.validation_rule == vr}
-
ruling.pend! unless ruling.pending?
-
end
-
end
-
-
@notification_groups = current_user.ssl_account.notification_groups.pluck(:friendly_name, :ref)
-
@notification_groups.insert(0, ['none', 'none']) #if @notification_groups.empty?
-
-
notification_group_subject = @certificate_order.notification_groups_subjects.where(created_page: 'csr').first
-
@slt_notification_group = [notification_group_subject.notification_group.ref] if notification_group_subject
-
-
@managed_csrs = (@certificate_order.ssl_account.all_csrs)
-
.sort_by{|arr| arr.common_name || ""}
-
.map{|arr| [(arr.friendly_name || arr.common_name || "")+' '+ arr.public_key_sha1, arr.ref]}
-
.delete_if{|arr| arr.second == nil}
-
@managed_csrs.insert(0, ['none', 'none'])
-
-
if params[:csr_ref]
-
@generated_csr = params[:csr_ref]
-
end
-
-
@is_reprocess = true
-
-
return render '/certificates/buy', :layout=>'application'
-
end
-
else
-
not_found
-
end
-
end
-
-
# POST /certificate_orders
-
# POST /certificate_orders.xml
-
def create
-
redirect_to new_order_url and return unless current_user
-
certificate_order = CertificateOrder.new(params[:certificate_order])
-
@certificate = Certificate.for_sale.find_by_product(params[:certificate][:product])
-
determine_eligibility_to_buy(@certificate, certificate_order)
-
@certificate_order = Order.setup_certificate_order(certificate: @certificate, certificate_order: certificate_order)
-
respond_to do |format|
-
if @certificate_order.save
-
if is_reseller? && (current_order.amount.cents >
-
current_user.ssl_account.funded_account.amount.cents)
-
format.html {redirect_to allocate_funds_for_order_path(:id=>
-
'certificate')}
-
else
-
format.html {redirect_to confirm_funds_path(:id=>'certificate_order')}
-
end
-
else
-
format.html { render(:template => "certificates/buy")}
-
end
-
end
-
end
-
-
# PUT /certificate_orders/1
-
# PUT /certificate_orders/1.xml
-
def update
-
respond_to do |format|
-
params[:certificate_order][:certificate_contents_attributes]['0'][:registrant_attributes][:country_code] =
-
params[:country_code] if params[:country_code]
-
-
is_smime_or_client = @certificate_order.certificate.is_smime_or_client?
-
if @certificate_order.update_attributes(params[:certificate_order])
-
cc = @certificate_order.certificate_content
-
original_state_phone_approve = cc.locked_registrant.blank? ? false : cc.locked_registrant.phone_number_approved
-
-
# TODO: Store LockedRegistrant Data in case of CS
-
setup_locked_registrant(
-
params[:certificate_order][:certificate_contents_attributes]['0'], cc
-
) if @certificate_order.certificate.requires_locked_registrant?
-
-
setup_reusable_registrant(@certificate_order.registrant) if params[:save_for_later]
-
-
if cc.csr_submitted? or cc.new?
-
cc.provide_info!
-
if current_user.ssl_account.is_registered_reseller?
-
@order = @certificate_order.order
-
unless @order.deducted_from.blank?
-
@deposit = @order.deducted_from
-
@profile = @deposit.billing_profile
-
end
-
unless is_smime_or_client
-
CertificateContent::CONTACT_ROLES.each do |role|
-
c = CertificateContact.new
-
r = current_user.ssl_account.reseller
-
CertificateContent::RESELLER_FIELDS_TO_COPY.each do |field|
-
c.send((field+'=').to_sym, r.send(field.to_sym))
-
end
-
c.company_name = r.organization
-
c.country = Country.find_by_name_caps(r.country.upcase).iso1_code if
-
Country.find_by_name_caps(r.country.upcase)
-
c.clear_roles
-
c.add_role! role
-
cc.certificate_contacts << c
-
cc.update_attribute(role+"_checkbox", true) unless
-
role==CertificateContent::ADMINISTRATIVE_ROLE
-
end
-
else
-
-
end
-
unless @certificate_order.certificate.is_ev?
-
cc.provide_contacts!
-
end
-
end
-
end
-
-
if current_user.is_super_user? && !original_state_phone_approve &&
-
!params[:certificate_order][:certificate_contents_attributes]['0'][:registrant_attributes][:phone].blank? &&
-
!params[:certificate_order][:certificate_contents_attributes]['0'][:registrant_attributes][:phone_number_approved].blank? &&
-
params[:certificate_order][:certificate_contents_attributes]['0'][:registrant_attributes][:phone_number_approved] == '1'
-
OrderNotifier.notify_phone_number_approve(@certificate_order, current_user.email).deliver
-
flash[:notice] = "Phone number approved and notification sent to this certificate order's owner."
-
end
-
-
if is_smime_or_client
-
format.html { redirect_to recipient_certificate_order_path(@ssl_slug, @certificate_order.ref) }
-
elsif @certificate_order.is_express_signup? || @certificate_order.skip_contacts_step?
-
format.html { redirect_to validation_destination(slug: @ssl_slug, certificate_order: @certificate_order) }
-
else #assume ev full signup process
-
format.html { redirect_to certificate_content_contacts_path(@ssl_slug, cc) }
-
end
-
format.xml { head :ok }
-
else
-
setup_registrant(
-
params[:certificate_order][:certificate_contents_attributes]['0'][:registrant_attributes]
-
)
-
format.html { render 'edit' }
-
format.xml { render :xml => @certificate_order.errors, :status => :unprocessable_entity }
-
end
-
end
-
end
-
-
def recipient
-
@assignee_id = nil
-
@iv_exists = nil
-
edit_locked_recipient = current_user.is_system_admins? && (params[:edit_locked_recipient] == 'true')
-
-
if params[:add_recipient] == 'true'
-
find_team_iv
-
-
if @assignee_id && !edit_locked_recipient
-
@certificate_order.update_column(:assignee_id, @assignee_id)
-
else
-
invite_recipient
-
end
-
-
if @iv_exists && @iv_exists.persisted?
-
if @certificate_order.locked_recipient.nil? || edit_locked_recipient
-
for_assignee = edit_locked_recipient ? @iv_exists.user_id : nil
-
LockedRecipient.create_for_co(@certificate_order, for_assignee)
-
end
-
edit_locked_recipient ? update_recipient(:locked) : update_recipient
-
# Local Registration Authority, validate IV
-
@iv_exists.update_column(:status, Contact::statuses[:validated]) if params[:lra]
-
end
-
-
if @iv_exists.nil? && @assignee_id.nil?
-
redirect_to :back, error: 'Something went wrong, please try again'
-
else
-
client_smime_validate
-
end
-
else
-
render :recipient
-
end
-
end
-
-
# PUT /certificate_orders/1
-
# PUT /certificate_orders/1.xml
-
def update_csr
-
if Settings.csr_domains_ui
-
managed_domains = params[:managed_domains]
-
additional_domains = ''
-
managed_domains.each do |domain|
-
additional_domains.concat(domain.gsub('csr-', '') + ' ')
-
end unless managed_domains.blank?
-
-
params[:certificate_order][:certificate_contents_attributes]['0'.to_sym][:additional_domains] = additional_domains.strip
-
end
-
-
if @certificate_order.certificate.is_single?
-
params[:certificate_order][:certificate_contents_attributes]['0'.to_sym][:additional_domains]=[]
-
elsif @certificate_order.certificate.is_premium_ssl?
-
params[:certificate_order][:certificate_contents_attributes]['0'.to_sym][:additional_domains]=
-
params[:certificate_order][:certificate_contents_attributes]['0'.to_sym][:additional_domains].
-
split(Certificate::DOMAINS_TEXTAREA_SEPARATOR)[0..2].join(" ")
-
end
-
-
@certificate_content=CertificateContent.new(
-
params[:certificate_order][:certificate_contents_attributes]['0'.to_sym]
-
.merge(rekey_certificate: true)
-
)
-
@certificate_order.has_csr=true #we are submitting a csr afterall
-
@certificate_content.certificate_order=@certificate_order
-
@certificate_content.preferred_reprocessing=true if eval("@#{CertificateOrder::REPROCESSING}")
-
-
da_billing = @certificate_order.domains_adjust_billing?
-
ucc_renew = true if da_billing && @certificate_order.renew_billing?
-
ucc_reprocess = true if da_billing && !params[:reprocessing].blank?
-
ucc_csr_submit = true if da_billing && !ucc_reprocess && !ucc_renew
-
domains_adjustment = ucc_reprocess || ucc_renew || ucc_csr_submit
-
-
respond_to do |format|
-
if @certificate_content.valid?
-
cc = @certificate_order.transfer_certificate_content(@certificate_content)
-
-
if params[:common_name] && !params[:common_name].empty?
-
if @certificate_order.certificate.is_single? or @certificate_order.certificate.is_wildcard?
-
cert_single_name = cc.certificate_names.where(is_common_name: true).first
-
-
if cert_single_name and cert_single_name.name.downcase != params[:common_name].downcase
-
cert_single_name.update_column(:name,
-
CertificateContent.non_wildcard_name(params[:common_name].downcase,false))
-
cert_single_name.domain_control_validations.delete_all # remove any previous validations
-
cert_single_name.candidate_email_addresses # start the queued job running
-
Delayed::Job.enqueue CertificateContent::OtherDcvsSatisyJob.new(@certificate_order.ssl_account,
-
cert_single_name) if @certificate_order.ssl_account && @certificate_order.certificate.is_server?
-
# Basic and High Assurance includes domain minus www
-
if CertificateContent.non_wildcard_name(params[:common_name].downcase,true) != cert_single_name.name
-
no_www=cc.certificate_names.create(is_common_name: false, name:
-
CertificateContent.non_wildcard_name(params[:common_name].downcase,true))
-
no_www.candidate_email_addresses # start the queued job running
-
Delayed::Job.enqueue CertificateContent::OtherDcvsSatisyJob.new(@certificate_order.ssl_account,
-
no_www) if @certificate_order.ssl_account && @certificate_order.certificate.is_server?
-
end
-
end
-
else
-
domains = cc.domains
-
unless domains.include? params[:common_name]
-
domains << params[:common_name]
-
cc.update_attribute(:domains, domains.join(' '))
-
end
-
-
common_name_domain = cc.certificate_names.where(is_common_name: true).first
-
common_name_domain.update_attribute(:is_common_name, false) if common_name_domain
-
cc.certificate_names.find_by_name(params[:common_name]).update_attribute(:is_common_name, true)
-
end
-
end
-
-
if domains_adjustment
-
o = params[:order]
-
order_params = {
-
co_ref: @certificate_order.ref,
-
cc_ref: cc.ref,
-
reprocess_ucc: ucc_reprocess,
-
renew_ucc: ucc_renew,
-
ucc_csr_submit: ucc_csr_submit,
-
wildcard_amount: o[:wildcard_amount],
-
nonwildcard_amount: o[:nonwildcard_amount],
-
order_description: o[:order_description],
-
order_amount: o[:adjustment_amount],
-
wildcard_count: o[:wildcard_count].to_i,
-
nonwildcard_count: o[:nonwildcard_count].to_i
-
}
-
-
# setting managed_csr and domains.
-
setup_managed_csr_domains(params)
-
-
# scheduling
-
schedule(params)
-
-
format.html { redirect_to new_order_path(@ssl_slug, order_params) }
-
else
-
if cc.pending_validation?
-
format.html { redirect_to certificate_order_path(@ssl_slug, @certificate_order) }
-
end
-
-
# setting managed_csr and domains.
-
setup_managed_csr_domains(params)
-
-
# scheduling
-
schedule(params)
-
-
format.html { redirect_to edit_certificate_order_path(@ssl_slug, @certificate_order) }
-
format.xml { head :ok }
-
end
-
else
-
if domains_adjustment
-
path = if ucc_reprocess
-
reprocess_certificate_order_path(@ssl_slug, @certificate_order)
-
else
-
edit_certificate_order_path(@ssl_slug, @certificate_order)
-
end
-
flash[:error] = "Please correct errors in this step. #{@certificate_content.errors.full_messages.join(', ')}."
-
format.html { redirect_to path }
-
else
-
@certificate = @certificate_order.certificate
-
format.html { render '/certificates/buy', :layout=>'application' }
-
format.xml { render :xml => @certificate_order.errors, :status => :unprocessable_entity }
-
end
-
end
-
end
-
end
-
-
def change_ext_order_number
-
if params[:num].blank?
-
@certificate_order.unchain_comodo
-
else
-
@certificate_order.update_column :external_order_number, params[:num]
-
@certificate_order.certificate_contents.last.update_column :ca_id, nil
-
end
-
SystemAudit.create(owner: current_user, target: @certificate_order,
-
action: "changed external order number to #{params[:num]}")
-
redirect_to certificate_order_path(@ssl_slug, @certificate_order)
-
end
-
-
# GET /certificate_orders/credits
-
# GET /certificate_orders/credits.xml
-
def credits
-
@certificate_orders = (current_user.is_admin? ?
-
CertificateOrder.where{(workflow_state=='paid') & (certificate_contents.workflow_state == "new")} :
-
current_user.ssl_account.cached_certificate_orders_credits).paginate(@p)
-
-
respond_to do |format|
-
format.html { render :action=>:index}
-
format.xml { render :xml => @certificate_orders }
-
end
-
end
-
-
def pending
-
@certificate_orders = (current_user.is_admin? ?
-
CertificateOrder.pending :
-
current_user.ssl_account.cached_certificate_orders_pending).paginate(@p)
-
-
respond_to do |format|
-
format.html { render :action=>:index}
-
format.xml { render :xml => @certificate_orders }
-
end
-
end
-
-
def filter_by_scope
-
@certificate_orders = (current_user.is_admin? ?
-
CertificateOrder.send(params[:id].to_sym) :
-
(current_user.role_symbols(current_user.ssl_account).join(',').split(',').include?(Role::INDIVIDUAL_CERTIFICATE) ?
-
(current_user.ssl_account.cached_certificate_orders.joins{:certificate_contents}.search_assigned(current_user.id).send(params[:id].to_sym)) :
-
(current_user.ssl_account.cached_certificate_orders.joins{:certificate_contents}.send(params[:id].to_sym))
-
)).paginate(@p)
-
-
respond_to do |format|
-
format.html { render :action=>:index}
-
format.xml { render :xml => @certificate_orders }
-
end
-
end
-
-
def order_by_csr
-
@certificate_orders = (current_user.is_admin? ?
-
CertificateOrder.unscoped{CertificateOrder.not_test} :
-
current_user.ssl_account.cached_certificate_orders.unscoped{
-
current_user.ssl_account.cached_certificate_orders.not_test}).order_by_csr.paginate(@p)
-
id=@ssl_account.id if @ssl_account
-
@certificate_orders = @certificate_orders.where{ssl_account_id==id} if(current_user.is_admin? and id)
-
-
respond_to do |format|
-
format.html { render :action=>:index}
-
format.xml { render :xml => @certificate_orders }
-
end
-
end
-
-
def filter_by
-
@certificate_orders = current_user.is_admin? ?
-
(@ssl_account.try(:certificate_orders) || CertificateOrder) : current_user.ssl_account.cached_certificate_orders
-
@certificate_orders = @certificate_orders.not_test.not_new.filter_by(params[:id]).paginate(@p)
-
-
respond_to do |format|
-
format.html { render :action=>:index}
-
format.xml { render :xml => @certificate_orders }
-
end
-
end
-
-
# GET /certificate_orders/credits
-
# GET /certificate_orders/credits.xml
-
def incomplete
-
@certificate_orders = (current_user.is_admin? ?
-
CertificateOrder.incomplete :
-
current_user.ssl_account.cached_certificate_orders_incomplete).paginate(@p)
-
-
respond_to do |format|
-
format.html { render :action=>:index}
-
format.xml { render :xml => @certificate_orders }
-
end
-
end
-
-
# GET /certificate_orders/credits
-
# GET /certificate_orders/credits.xml
-
def reprocessing
-
@certificate_orders = (current_user.is_admin? ?
-
CertificateOrder.reprocessing :
-
current_user.ssl_account.cached_certificate_orders.reprocessing).paginate(@p)
-
-
respond_to do |format|
-
format.html { render :action=>:index}
-
format.xml { render :xml => @certificate_orders }
-
end
-
end
-
-
# DELETE /certificate_orders/1
-
# DELETE /certificate_orders/1.xml
-
def destroy
-
@certificate_order.destroy
-
-
respond_to do |format|
-
format.html { redirect_to(certificate_orders_url) }
-
format.xml { head :ok }
-
end
-
end
-
-
def developer
-
-
end
-
-
def developers
-
not_found and return unless is_sandbox?
-
end
-
-
def download
-
t=File.new(@certificate_order.certificate_content.csr.signed_certificate.
-
create_signed_cert_zip_bundle({components: true, is_windows: is_client_windows?}), "r")
-
# End of the block automatically closes the file.
-
# Send it using the right mime type, with a download window and some nice file name.
-
send_file t.path, :type => 'application/zip', :disposition => 'attachment',
-
:filename => @certificate_order.friendly_common_name+'.zip'
-
# The temp file will be deleted some time...
-
t.close
-
end
-
-
def download_other
-
t=File.new(@certificate_order.certificate_content.csr.signed_certificate.
-
create_signed_cert_zip_bundle(is_windows: is_client_windows?), "r")
-
# End of the block automatically closes the file.
-
# Send it using the right mime type, with a download window and some nice file name.
-
send_file t.path, :type => 'application/zip', :disposition => 'attachment',
-
:filename => @certificate_order.friendly_common_name+'.zip'
-
# The temp file will be deleted some time...
-
t.close
-
end
-
-
# this function allows the customer to resubmit a new csr even while the order is being processed
-
def start_over
-
@certificate_order.start_over! unless @certificate_order.blank?
-
flash[:notice] = "certificate order #{@certificate_order.ref} has been canceled and restarted"
-
end
-
-
def parse_csr
-
c = Certificate.for_sale.find_by_product(params[:certificate])
-
co = CertificateOrder.new(duration: 1)
-
@cc = co.certificate_contents.build(certificate_order: co, ajax_check_csr: true)
-
co = Order.setup_certificate_order(certificate: c, certificate_order: co)
-
@cc.csr = Csr.new(body: params[:csr])
-
@cc.valid?
-
rescue
-
end
-
-
def admin_update
-
if current_user.is_system_admins? or
-
(current_user.ssl_account.epki_registrant and
-
current_user.ssl_account.epki_registrant.applies_to_certificate_order?(@certificate_order))
-
if params[:validate_iv] || params[:validate_ov]
-
admin_validate
-
elsif params[:unvalidate_iv] || params[:unvalidate_ov]
-
admin_unvalidate
-
else
-
respond_to do |format|
-
if @certificate_order.update_attributes(params[:certificate_order])
-
format.js { render :json=>@certificate_order.to_json}
-
else
-
format.js { render :json=>@certificate_order.errors.to_json}
-
end
-
end
-
end
-
end
-
end
-
-
def switch_from_comodo
-
returnObj = {}
-
-
if current_user
-
co = CertificateOrder.find_by_ref(params[:certificate_order_id])
-
-
if co
-
co.unchain_comodo
-
returnObj['status'] = 'success'
-
else
-
returnObj['status'] = 'no-exist-cert-order'
-
end
-
else
-
returnObj['status'] = 'no-user'
-
end
-
-
render :json => returnObj
-
end
-
-
def register_domains
-
returnObj = {}
-
@certificate_order = CertificateOrder.find_by_ref(params['id'])
-
-
if current_user
-
@certificate_order.certificate_content.locked_registrant.update_attribute(:domains, params['domains']) if @certificate_order
-
returnObj['status'] = 'success'
-
else
-
returnObj['status'] = 'no-user'
-
end
-
-
render :json => returnObj
-
end
-
-
private
-
-
def smime_client_create
-
@certificate = Certificate.find params[:certificate_id]
-
smime_client_parse_emails
-
-
if @certificate && @emails.any?
-
redirect_to new_order_path(@ssl_slug,
-
emails: @emails,
-
certificate: @certificate,
-
smime_client_enrollment: true
-
)
-
else
-
flash[:error] = "Please enter at least one valid email."
-
render :smime_client_enrollment
-
end
-
end
-
-
def smime_client_init
-
find_tier
-
@certificates = Certificate.get_smime_client_products(@tier)
-
@certificate ||= @certificates.first
-
-
co = CertificateOrder.new(
-
duration: 2,
-
ssl_account: (current_user.blank? ? nil : current_user.ssl_account),
-
has_csr: false
-
)
-
co.certificate_contents << CertificateContent.new(domains: [])
-
@certificate_order = Order.setup_certificate_order(
-
certificate: @certificate, certificate_order: co
-
)
-
end
-
-
def smime_client_duration
-
@certificate = Certificate.find params[:certificate_id]
-
partial = render_to_string(
-
partial: 'certificate_orders/smime_client_enrollment/duration_form',
-
layout: false
-
)
-
render json: {content: partial}, status: :ok
-
end
-
-
def client_smime_validate
-
co = @certificate_order
-
cc = co.certificate_content
-
validations = co.certificate.client_smime_validations
-
validated = if validations == 'iv_ov'
-
if @iv_exists.validated?
-
if co.registrant.epki_agreement?
-
co.registrant.applies_to_certificate_order?(co)
-
else
-
(co.locked_registrant || co.registrant).validated?
-
end
-
end
-
elsif validations == 'iv'
-
@iv_exists.validated?
-
else
-
true
-
end
-
-
if co.certificate.is_client_pro? && params[:saved_contacts].blank?
-
cc.pend_validation! if !(cc.pending_validation? or cc.issued?)
-
redirect_to document_upload_certificate_order_validation_path(
-
@ssl_slug, certificate_order_id: co.ref
-
)
-
else
-
if validated
-
cc.validate! unless cc.validated?
-
co.copy_iv_ov_validation_history(validations)
-
redirect_to certificate_order_path(@ssl_slug, co.ref)
-
else
-
cc.pend_validation! if !(cc.pending_validation? or cc.issued?)
-
redirect_to document_upload_certificate_order_validation_path(
-
@ssl_slug, certificate_order_id: co.ref
-
)
-
end
-
end
-
end
-
-
def admin_validate
-
cc = @certificate_order.certificate_content
-
ov = @certificate_order.locked_registrant
-
lr = @certificate_order.locked_recipient
-
-
if @certificate_order.certificate.is_smime_or_client?
-
iv = @certificate_order.get_team_iv
-
ov_iv = @certificate_order.certificate.requires_locked_registrant?
-
-
if (params[:validate_iv] && iv && !iv.validated?)
-
iv.validated!
-
lr.validated! if lr && (iv.email == lr.email)
-
end
-
-
admin_validate_ov(ov)
-
if (ov_iv && @certificate_order.iv_ov_validated?) || (!ov_iv && @certificate_order.iv_validated?)
-
cc.validate! if !(cc.validated? or cc.pending_validation? or cc.issued?)
-
end
-
else
-
admin_validate_ov(ov)
-
# if ov.validated? && @certificate_order.domains_validated?
-
# @certificate_order.apply_for_certificate(
-
# mapping: @certificate_order.certificate_content.ca,
-
# current_user: current_user
-
# )
-
# end
-
end
-
redirect_to certificate_order_path(@ssl_slug, @certificate_order.ref),
-
notice: "Certificate order was successfully validated."
-
end
-
-
def admin_validate_ov(ov)
-
if params[:validate_ov] && ov && !ov.validated?
-
ov.validated!
-
unless ov.parent_id.nil?
-
parent = Contact.find(ov.parent_id)
-
parent.validated! if parent && !parent.validated?
-
end
-
end
-
end
-
-
def admin_unvalidate
-
cc = @certificate_order.certificate_content
-
ov = @certificate_order.locked_registrant
-
lr = @certificate_order.locked_recipient
-
vt = params[:unvalidate_type]
-
-
if @certificate_order.certificate.is_smime_or_client?
-
iv = @certificate_order.get_team_iv
-
if params[:unvalidate_iv] && vt && iv && lr && (iv.email == lr.email)
-
iv.send("#{vt}!")
-
end
-
lr.send("#{vt}!") if params[:unvalidate_iv] && lr
-
admin_unvalidate_ov(ov)
-
unless @certificate_order.iv_ov_validated?
-
cc.pend_validation! unless cc.pending_validation?
-
end
-
else
-
admin_unvalidate_ov(ov)
-
if !ov.validated? &&
-
(!@certificate_order.certificate.is_code_signing? ||
-
(@certificate_order.certificate.is_code_signing? && !@certificate_order.csr.blank?))
-
@certificate_order.apply_for_certificate(
-
mapping: @certificate_order.certificate_content.ca,
-
current_user: current_user
-
)
-
end
-
end
-
redirect_to certificate_order_path(@ssl_slug, @certificate_order.ref),
-
notice: "Certificate order was successfully updated."
-
end
-
-
def admin_unvalidate_ov(ov)
-
vt = params[:unvalidate_type]
-
if params[:unvalidate_ov] && vt && ov
-
ov.send("#{vt}!")
-
unless ov.parent_id.nil?
-
parent = Contact.find(ov.parent_id)
-
parent.send("#{vt}!") if parent
-
end
-
end
-
end
-
-
def registrants_on_edit
-
setup_registrant
-
if params[:registrant] == 'false'
-
setup_registrant_from_locked
-
else
-
if @csr
-
@registrant.company_name = @csr.organization unless @csr.organization.blank?
-
@registrant.department = @csr.organization_unit unless @csr.organization_unit.blank?
-
@registrant.city = @csr.locality unless @csr.locality.blank?
-
@registrant.state = @csr.state unless @csr.state.blank?
-
@registrant.email = @csr.email unless @csr.email.blank?
-
@registrant.country = @csr.country unless @csr.country.blank?
-
end
-
end
-
end
-
-
def invite_recipient
-
ssl = @certificate_order.ssl_account
-
user_exists = User.find_by(email: params[:email])
-
if user_exists
-
user_exists_for_team = ssl.users.find_by(id: user_exists.id)
-
-
if user_exists_for_team
-
@iv_exists = ssl.individual_validations.find_by(user_id: user_exists_for_team.id)
-
end
-
-
unless @iv_exists
-
# Add IV for user to team.
-
@iv_exists = ssl.individual_validations.create(
-
first_name: params[:first_name],
-
last_name: params[:last_name],
-
email: user_exists.email,
-
status: user_exists_for_team ? Contact::statuses[:validated] : Contact::statuses[:in_progress],
-
user_id: user_exists.id
-
)
-
end
-
-
# Add user to team w/role individual_certificate
-
unless user_exists_for_team
-
user_exists.ssl_accounts << ssl
-
user_exists.set_roles_for_account(
-
ssl, [Role::get_individual_certificate_id]
-
)
-
end
-
-
unless current_user.is_system_admins? && (params[:edit_locked_recipient] == 'true')
-
@certificate_order.update_column(:assignee_id, user_exists.id)
-
end
-
else
-
invite_new_recipient
-
end
-
end
-
-
def invite_new_recipient
-
new_user = current_user.invite_new_user({user: {
-
email: params[:email],
-
first_name: params[:first_name],
-
last_name: params[:last_name],
-
}})
-
if new_user.persisted?
-
invite_recipient
-
end
-
end
-
-
def find_team_iv
-
attrs = {}
-
attrs[:id] = params[:saved_contacts] unless params[:saved_contacts].blank?
-
attrs[:email] = params[:email].strip if attrs.empty? && !params[:email].blank?
-
unless attrs.empty?
-
@iv_exists = @certificate_order.ssl_account
-
.individual_validations.find_by(attrs)
-
end
-
@assignee_id = @iv_exists.user_id if @iv_exists
-
end
-
-
def update_recipient(locked=nil)
-
@certificate_order.reload
-
current_recipient = locked ? @certificate_order.locked_recipient : @iv_exists
-
if current_recipient
-
current_recipient.update(
-
%w{first_name last_name email}.inject({}) do |all, key|
-
all[key.to_sym] = params[key.to_sym] unless params[key.to_sym].blank?
-
all
-
end
-
)
-
end
-
end
-
-
def set_row_page
-
preferred_row_count = current_user.preferred_cert_order_row_count
-
@per_page = params[:per_page] || preferred_row_count.or_else("10")
-
CertificateOrder.per_page = @per_page if CertificateOrder.per_page != @per_page
-
-
if @per_page != preferred_row_count
-
current_user.preferred_cert_order_row_count = @per_page
-
current_user.save(validate: false)
-
end
-
-
@p = {page: (params[:page] || 1), per_page: @per_page}
-
end
-
-
def recert(action)
-
instance_variable_set("@"+action,CertificateOrder.unscoped.find_by_ref(params[:id]))
-
instance_variable_get("@"+action)
-
end
-
-
def load_certificate_order
-
if current_user
-
@certificate_order=current_user.certificate_order_by_ref(params[:id])
-
-
if @certificate_order.nil?
-
co = current_user.ssl_accounts.includes(:certificate_orders).map(&:certificate_orders)
-
.flatten.find{|c| c.ref == params[:id]}
-
if co
-
@certificate_order = co
-
if co.ssl_account != current_user.ssl_account && current_user.ssl_accounts.include?(co.ssl_account)
-
-
current_user.set_default_ssl_account(co.ssl_account)
-
set_ssl_slug
-
end
-
end
-
end
-
end
-
render 'site/404_not_found', status: 404 unless @certificate_order
-
end
-
-
def construct_special_fields
-
if params[:certificate_order]
-
new_attributes = params[:certificate_order][:certificate_contents_attributes]['0'][:registrant_attributes] if params[:certificate_order][:certificate_contents_attributes]
-
if new_attributes && new_attributes.any?
-
cert_special_fields = @certificate_order.certificate.special_fields
-
special_fields = {}
-
if cert_special_fields.is_a?(Array) && cert_special_fields.any?
-
new_attributes.each do |k, v|
-
special_fields[k] = v if cert_special_fields.include?(k) && !v.blank?
-
end
-
new_attributes.delete_if {|rsp| cert_special_fields.include?(rsp)}
-
end
-
new_attributes.merge!(
-
'special_fields' => (special_fields.blank? ? nil : special_fields)
-
)
-
end
-
end
-
end
-
-
def setup_registrant(registrant_params=nil)
-
cc = @certificate_order.certificate_content
-
@registrant = unless cc.registrant.blank?
-
cc.registrant.update(registrant_params) if registrant_params
-
cc.registrant
-
else
-
registrant_params ? cc.build_registrant(registrant_params) : cc.build_registrant
-
end
-
setup_reusable_registrant(@registrant)
-
end
-
-
def setup_registrant_from_locked
-
locked_registrant = @certificate_order.certificate_content.locked_registrant
-
unless locked_registrant.blank?
-
@registrant.assumed_name = locked_registrant.assumed_name
-
@registrant.duns_number = locked_registrant.duns_number
-
@registrant.department = locked_registrant.department
-
@registrant.po_box = locked_registrant.po_box
-
@registrant.address1 = locked_registrant.address1
-
@registrant.address2 = locked_registrant.address2
-
@registrant.address3 = locked_registrant.address3
-
@registrant.city = locked_registrant.city
-
@registrant.state = locked_registrant.state
-
@registrant.postal_code = locked_registrant.postal_code
-
@registrant.country = locked_registrant.country
-
@registrant.title = locked_registrant.title
-
@registrant.first_name = locked_registrant.first_name
-
@registrant.last_name = locked_registrant.last_name
-
@registrant.email = locked_registrant.email
-
@registrant.phone = locked_registrant.phone
-
@registrant.phone_number_approved = locked_registrant.phone_number_approved
-
@registrant.country_code = locked_registrant.country_code
-
@registrant.status = locked_registrant.status
-
@registrant.parent_id = locked_registrant.parent_id
-
@registrant.special_fields = locked_registrant.special_fields
-
end
-
end
-
-
def setup_locked_registrant(cc_params=nil, cc)
-
if cc_params && cc_params[:registrant_attributes]
-
cc_params[:registrant_attributes].delete('id')
-
-
unless params[:saved_contacts].blank?
-
cc_params[:registrant_attributes].merge(
-
{'parent_id' => params[:saved_contacts].to_i}
-
)
-
end
-
-
if cc.locked_registrant.blank?
-
cc.create_locked_registrant(cc_params[:registrant_attributes])
-
cc.locked_registrant.save!
-
elsif current_user.is_system_admins?
-
cc.locked_registrant.update(cc_params[:registrant_attributes])
-
end
-
setup_reusable_registrant(cc.locked_registrant)
-
end
-
end
-
-
def setup_reusable_registrant(from_registrant)
-
if params[:save_for_later] &&
-
from_registrant &&
-
from_registrant.persisted? &&
-
from_registrant.parent_id.nil? &&
-
@reusable_registrant.nil?
-
-
attr = from_registrant.attributes.delete_if do |k,v|
-
%w{created_at updated_at id}.include?(k)
-
end
-
attr.merge!(
-
'contactable_id' => @certificate_order.ssl_account.id,
-
'contactable_type' => 'SslAccount',
-
'type' => 'Registrant'
-
)
-
@reusable_registrant = Registrant.create(attr)
-
if @reusable_registrant.persisted?
-
from_registrant.update_column(:parent_id, @reusable_registrant.id)
-
end
-
end
-
end
-
-
def set_schedule_value
-
@schedule_simple_type = [
-
['Hourly', '1'],
-
['Daily (at midnight)', '2'],
-
['Weekly (on Sunday)', '3'],
-
['Monthly (on the 1st)', '4'],
-
['Yearly (on 1st Jan)', '5']
-
]
-
-
@schedule_weekdays = [
-
['Sunday', '0'], ['Monday', '1'], ['Tuesday', '2'], ['Wednesday', '3'],
-
['Thursday', '4'], ['Friday', '5'], ['Saturday', '6']
-
]
-
-
@schedule_months = [
-
['January', '1'], ['Febrary', '2'], ['March', '3'], ['April', '4'], ['May', '5'], ['June', '6'],
-
['July', '7'], ['August', '8'], ['September', '9'], ['October', '10'], ['November', '11'], ['December', '12']
-
]
-
-
@schedule_days = [
-
['1', '1'], ['2', '2'], ['3', '3'], ['4', '4'], ['5', '5'], ['6', '6'],
-
['7', '7'], ['8', '8'], ['9', '9'], ['10', '10'], ['11', '11'], ['12', '12'],
-
['13', '13'], ['14', '14'], ['15', '15'], ['16', '16'], ['17', '17'], ['18', '18'],
-
['19', '19'], ['20', '20'], ['21', '21'], ['22', '22'], ['23', '23'], ['24', '24'],
-
['25', '25'], ['26', '26'], ['27', '27'], ['28', '28'], ['29', '29'], ['30', '30'], ['31', '31']
-
]
-
-
@schedule_hours = [
-
['0', '0'], ['1', '1'], ['2', '2'], ['3', '3'], ['4', '4'], ['5', '5'], ['6', '6'],
-
['7', '7'], ['8', '8'], ['9', '9'], ['10', '10'], ['11', '11'], ['12', '12'],
-
['13', '13'], ['14', '14'], ['15', '15'], ['16', '16'], ['17', '17'], ['18', '18'],
-
['19', '19'], ['20', '20'], ['21', '21'], ['22', '22'], ['23', '23']
-
]
-
-
@schedule_minutes = [
-
['0', '0'], ['1', '1'], ['2', '2'], ['3', '3'], ['4', '4'], ['5', '5'], ['6', '6'],
-
['7', '7'], ['8', '8'], ['9', '9'], ['10', '10'], ['11', '11'], ['12', '12'],
-
['13', '13'], ['14', '14'], ['15', '15'], ['16', '16'], ['17', '17'], ['18', '18'],
-
['19', '19'], ['20', '20'], ['21', '21'], ['22', '22'], ['23', '23'], ['24', '24'],
-
['25', '25'], ['26', '26'], ['27', '27'], ['28', '28'], ['29', '29'], ['30', '30'],
-
['31', '31'], ['32', '32'], ['33', '33'], ['34', '34'], ['35', '35'], ['36', '36'],
-
['37', '37'], ['38', '38'], ['39', '39'], ['40', '40'], ['41', '41'], ['42', '42'],
-
['43', '43'], ['44', '44'], ['45', '45'], ['46', '46'], ['47', '47'], ['48', '48'],
-
['49', '49'], ['50', '50'], ['51', '51'], ['52', '52'], ['53', '53'], ['54', '54'],
-
['55', '55'], ['56', '56'], ['57', '57'], ['58', '58'], ['59', '59']
-
]
-
end
-
-
def schedule(params)
-
# Create or Update notification group
-
if params[:schedule_type] == 'none' && params[:notification_group] != 'none'
-
notification_group = current_user.ssl_account.notification_groups.includes{:notification_groups_subjects}.where(ref: params[:notification_group]).first
-
-
unless notification_group
-
flash[:error] = "Some error occurs while getting notification group data. Please try again."
-
@certificate = @certificate_order.certificate
-
-
format.html { render '/certificates/buy', :layout=>'application' }
-
end
-
else
-
# Saving notification group info
-
notification_group = current_user.ssl_account.notification_groups.includes{:notification_groups_subjects}.find_by_friendly_name('ng-' + @certificate_order.ref)
-
-
if notification_group.nil?
-
notification_group = NotificationGroup.new(
-
friendly_name: 'ng-' + @certificate_order.ref,
-
scan_port: '443',
-
notify_all: true,
-
ssl_account: current_user.ssl_account,
-
status: false,
-
)
-
end
-
-
# Saving notification group triggers
-
['60', '30', '15', '0', '-15'].uniq.sort{|a, b| a.to_i <=> b.to_i}.reverse.each_with_index do |rt, i|
-
notification_group.preferred_notification_group_triggers = rt.or_else(nil), ReminderTrigger.find(i + 1)
-
end
-
-
unless notification_group.save
-
flash[:error] = "Some error occurs while saving notification group data. Please try again."
-
@certificate = @certificate_order.certificate
-
-
format.html { render '/certificates/buy', :layout=>'application' }
-
end
-
end
-
-
# if params[:notification_group] == 'none'
-
# # Saving notification group info
-
# notification_group = NotificationGroup.new(
-
# friendly_name: 'ng-' + @certificate_order.ref,
-
# scan_port: '443',
-
# notify_all: true,
-
# ssl_account: current_user.ssl_account,
-
# status: false,
-
# )
-
#
-
# # Saving notification group triggers
-
# ['60', '30', '15', '0', '-15'].uniq.sort{|a, b| a.to_i <=> b.to_i}.reverse.each_with_index do |rt, i|
-
# notification_group.preferred_notification_group_triggers = rt.or_else(nil), ReminderTrigger.find(i + 1)
-
# end
-
#
-
# unless notification_group.save
-
# flash[:error] = "Some error occurs while saving notification group data. Please try again."
-
# @certificate = @certificate_order.certificate
-
#
-
# format.html { render '/certificates/buy', :layout=>'application' }
-
# end
-
# else
-
# notification_group = current_user.ssl_account.notification_groups.where(ref: params[:notification_group]).first
-
#
-
# unless notification_group
-
# flash[:error] = "Some error occurs while getting notification group data. Please try again."
-
# @certificate = @certificate_order.certificate
-
#
-
# format.html { render '/certificates/buy', :layout=>'application' }
-
# end
-
# end
-
-
# Saving certificate order tag
-
is_exist = notification_group.certificate_orders.where(id: @certificate_order.id)
-
notification_group.notification_groups_subjects.build(
-
subjectable_type: 'CertificateOrder', subjectable_id: @certificate_order.id
-
).save if is_exist.empty?
-
-
# Saving subject tags
-
# new_tags = @certificate_order.certificate_content.certificate_names.pluck(:id).map{ |val| val.to_s }
-
new_tags = @certificate_order.certificate_contents.map(&:certificate_names).flatten.compact.map{|cn| cn.id.to_s}
-
current_tags = notification_group.notification_groups_subjects
-
.where(subjectable_type: ['CertificateName', nil]).pluck(:domain_name, :subjectable_id)
-
.map{ |arr| arr[0].blank? ? arr[1].to_s : (arr[1].blank? ? arr[0] : (arr[0] + '---' + arr[1].to_s)) }
-
add_tags = new_tags - current_tags
-
add_tags.each do |subject|
-
notification_group.notification_groups_subjects.build(
-
subjectable_type: 'CertificateName', subjectable_id: subject
-
).save
-
end
-
-
# Saving contact tags
-
current_tags = notification_group.notification_groups_contacts.where(email_address: current_user.email)
-
notification_group.notification_groups_contacts.build(
-
email_address: current_user.email
-
).save if current_tags.empty?
-
-
# Saving schedule
-
if (params[:schedule_type] == 'none' && params[:notification_group] == 'none') || params[:schedule_type] == 'simple'
-
current_schedules = notification_group.schedules.pluck(:schedule_type)
-
unless current_schedules.include? 'Simple'
-
schedule_value_value =
-
params[:schedule_type] == 'none' ?
-
'2' :
-
(params[:schedule_simple_type] ? params[:schedule_simple_type] : '2')
-
-
notification_group.schedules.destroy_all
-
notification_group.schedules.build(
-
schedule_type: 'Simple',
-
schedule_value: schedule_value_value
-
).save
-
end
-
elsif params[:schedule_type] == 'custom'
-
current_schedules = notification_group.schedules.pluck(:schedule_type)
-
if current_schedules.include? 'Simple'
-
notification_group.schedules.destroy_all
-
end
-
-
# Weekday
-
current_schedules = notification_group.schedules.where(schedule_type: 'Weekday').pluck(:schedule_value)
-
if params[:weekday_type] == 'true'
-
unless current_schedules.include? 'All'
-
notification_group.schedules.where(schedule_type: 'Weekday').destroy_all
-
notification_group.schedules.build(
-
schedule_type: 'Weekday',
-
schedule_value: 'All'
-
).save
-
end
-
else
-
params[:weekday_custom_list] ||= []
-
new_weekdays = params[:weekday_custom_list] - current_schedules
-
old_weekdays = current_schedules - params[:weekday_custom_list]
-
-
notification_group.schedules.where(schedule_type: 'Weekday', schedule_value: old_weekdays).destroy_all
-
new_weekdays.each do |weekday|
-
notification_group.schedules.build(
-
schedule_type: 'Weekday',
-
schedule_value: weekday
-
).save
-
end
-
end
-
-
# Month
-
current_schedules = notification_group.schedules.where(schedule_type: 'Month').pluck(:schedule_value)
-
if params[:month_type] == 'true'
-
unless current_schedules.include? 'All'
-
notification_group.schedules.where(schedule_type: 'Month').destroy_all
-
notification_group.schedules.build(
-
schedule_type: 'Month',
-
schedule_value: 'All'
-
).save
-
end
-
else
-
params[:month_custom_list] ||= []
-
new_months = params[:month_custom_list] - current_schedules
-
old_months = current_schedules - params[:month_custom_list]
-
-
notification_group.schedules.where(schedule_type: 'Month', schedule_value: old_months).destroy_all
-
new_months.each do |month|
-
notification_group.schedules.build(
-
schedule_type: 'Month',
-
schedule_value: month
-
).save
-
end
-
end
-
-
# Day
-
current_schedules = notification_group.schedules.where(schedule_type: 'Day').pluck(:schedule_value)
-
if params[:day_type] == 'true'
-
unless current_schedules.include? 'All'
-
notification_group.schedules.where(schedule_type: 'Day').destroy_all
-
notification_group.schedules.build(
-
schedule_type: 'Day',
-
schedule_value: 'All'
-
).save
-
end
-
else
-
params[:day_custom_list] ||= []
-
new_days = params[:day_custom_list] - current_schedules
-
old_days = current_schedules - params[:day_custom_list]
-
-
notification_group.schedules.where(schedule_type: 'Day', schedule_value: old_days).destroy_all
-
new_days.each do |day|
-
notification_group.schedules.build(
-
schedule_type: 'Day',
-
schedule_value: day
-
).save
-
end
-
end
-
-
# Hour
-
current_schedules = notification_group.schedules.where(schedule_type: 'Hour').pluck(:schedule_value)
-
if params[:hour_type] == 'true'
-
unless current_schedules.include? 'All'
-
notification_group.schedules.where(schedule_type: 'Hour').destroy_all
-
notification_group.schedules.build(
-
schedule_type: 'Hour',
-
schedule_value: 'All'
-
).save
-
end
-
else
-
params[:hour_custom_list] ||= []
-
new_hours = params[:hour_custom_list] - current_schedules
-
old_hours = current_schedules - params[:hour_custom_list]
-
-
notification_group.schedules.where(schedule_type: 'Hour', schedule_value: old_hours).destroy_all
-
new_hours.each do |hour|
-
notification_group.schedules.build(
-
schedule_type: 'Hour',
-
schedule_value: hour
-
).save
-
end
-
end
-
-
# Minute
-
current_schedules = notification_group.schedules.where(schedule_type: 'Minute').pluck(:schedule_value)
-
if params[:minute_type] == 'true'
-
unless current_schedules.include? 'All'
-
notification_group.schedules.where(schedule_type: 'Minute').destroy_all
-
notification_group.schedules.build(
-
schedule_type: 'Minute',
-
schedule_value: 'All'
-
).save
-
end
-
else
-
params[:minute_custom_list] ||= []
-
new_minutes = params[:minute_custom_list] - current_schedules
-
old_minutes = current_schedules - params[:minute_custom_list]
-
-
notification_group.schedules.where(schedule_type: 'Minute', schedule_value: old_minutes).destroy_all
-
new_minutes.each do |minute|
-
notification_group.schedules.build(
-
schedule_type: 'Minute',
-
schedule_value: minute
-
).save
-
end
-
end
-
end
-
-
# if params[:notification_group] == 'none'
-
# if params[:schedule_type] == 'true'
-
# current_schedules = notification_group.schedules.pluck(:schedule_type)
-
# unless current_schedules.include? 'Simple'
-
# notification_group.schedules.destroy_all
-
#
-
# notification_group.schedules.build(
-
# schedule_type: 'Simple',
-
# schedule_value: params[:schedule_simple_type]
-
# ).save
-
# end
-
# else
-
# current_schedules = notification_group.schedules.pluck(:schedule_type)
-
# if current_schedules.include? 'Simple'
-
# notification_group.schedules.destroy_all
-
# end
-
#
-
# # Weekday
-
# current_schedules = notification_group.schedules.where(schedule_type: 'Weekday').pluck(:schedule_value)
-
# if params[:weekday_type] == 'true'
-
# unless current_schedules.include? 'All'
-
# notification_group.schedules.where(schedule_type: 'Weekday').destroy_all
-
# notification_group.schedules.build(
-
# schedule_type: 'Weekday',
-
# schedule_value: 'All'
-
# ).save
-
# end
-
# else
-
# params[:weekday_custom_list] ||= []
-
# new_weekdays = params[:weekday_custom_list] - current_schedules
-
# old_weekdays = current_schedules - params[:weekday_custom_list]
-
#
-
# notification_group.schedules.where(schedule_type: 'Weekday', schedule_value: old_weekdays).destroy_all
-
# new_weekdays.each do |weekday|
-
# notification_group.schedules.build(
-
# schedule_type: 'Weekday',
-
# schedule_value: weekday
-
# ).save
-
# end
-
# end
-
#
-
# # Month
-
# current_schedules = notification_group.schedules.where(schedule_type: 'Month').pluck(:schedule_value)
-
# if params[:month_type] == 'true'
-
# unless current_schedules.include? 'All'
-
# notification_group.schedules.where(schedule_type: 'Month').destroy_all
-
# notification_group.schedules.build(
-
# schedule_type: 'Month',
-
# schedule_value: 'All'
-
# ).save
-
# end
-
# else
-
# params[:month_custom_list] ||= []
-
# new_months = params[:month_custom_list] - current_schedules
-
# old_months = current_schedules - params[:month_custom_list]
-
#
-
# notification_group.schedules.where(schedule_type: 'Month', schedule_value: old_months).destroy_all
-
# new_months.each do |month|
-
# notification_group.schedules.build(
-
# schedule_type: 'Month',
-
# schedule_value: month
-
# ).save
-
# end
-
# end
-
#
-
# # Day
-
# current_schedules = notification_group.schedules.where(schedule_type: 'Day').pluck(:schedule_value)
-
# if params[:day_type] == 'true'
-
# unless current_schedules.include? 'All'
-
# notification_group.schedules.where(schedule_type: 'Day').destroy_all
-
# notification_group.schedules.build(
-
# schedule_type: 'Day',
-
# schedule_value: 'All'
-
# ).save
-
# end
-
# else
-
# params[:day_custom_list] ||= []
-
# new_days = params[:day_custom_list] - current_schedules
-
# old_days = current_schedules - params[:day_custom_list]
-
#
-
# notification_group.schedules.where(schedule_type: 'Day', schedule_value: old_days).destroy_all
-
# new_days.each do |day|
-
# notification_group.schedules.build(
-
# schedule_type: 'Day',
-
# schedule_value: day
-
# ).save
-
# end
-
# end
-
#
-
# # Hour
-
# current_schedules = notification_group.schedules.where(schedule_type: 'Hour').pluck(:schedule_value)
-
# if params[:hour_type] == 'true'
-
# unless current_schedules.include? 'All'
-
# notification_group.schedules.where(schedule_type: 'Hour').destroy_all
-
# notification_group.schedules.build(
-
# schedule_type: 'Hour',
-
# schedule_value: 'All'
-
# ).save
-
# end
-
# else
-
# params[:hour_custom_list] ||= []
-
# new_hours = params[:hour_custom_list] - current_schedules
-
# old_hours = current_schedules - params[:hour_custom_list]
-
#
-
# notification_group.schedules.where(schedule_type: 'Hour', schedule_value: old_hours).destroy_all
-
# new_hours.each do |hour|
-
# notification_group.schedules.build(
-
# schedule_type: 'Hour',
-
# schedule_value: hour
-
# ).save
-
# end
-
# end
-
#
-
# # Minute
-
# current_schedules = notification_group.schedules.where(schedule_type: 'Minute').pluck(:schedule_value)
-
# if params[:minute_type] == 'true'
-
# unless current_schedules.include? 'All'
-
# notification_group.schedules.where(schedule_type: 'Minute').destroy_all
-
# notification_group.schedules.build(
-
# schedule_type: 'Minute',
-
# schedule_value: 'All'
-
# ).save
-
# end
-
# else
-
# params[:minute_custom_list] ||= []
-
# new_minutes = params[:minute_custom_list] - current_schedules
-
# old_minutes = current_schedules - params[:minute_custom_list]
-
#
-
# notification_group.schedules.where(schedule_type: 'Minute', schedule_value: old_minutes).destroy_all
-
# new_minutes.each do |minute|
-
# notification_group.schedules.build(
-
# schedule_type: 'Minute',
-
# schedule_value: minute
-
# ).save
-
# end
-
# end
-
# end
-
# end
-
end
-
-
def setup_managed_csr_domains(params)
-
# if params[:add_to_manager] && params[:add_to_manager] == 'true'
-
# managed_csr = ManagedCsr.new
-
# managed_csr.body = params[:certificate_order][:certificate_contents_attributes]['0'.to_sym][:signing_request]
-
# managed_csr.friendly_name = managed_csr.common_name || managed_csr.sha1_hash
-
# managed_csr.ssl_account_id = current_user.ssl_account.id
-
#
-
# unless managed_csr.save
-
# flash[:error] = "Some error occurs while adding this csr to the csr manager."
-
# @certificate = @certificate_order.certificate
-
#
-
# format.html { render '/certificates/buy', :layout=>'application' }
-
# end
-
#
-
# @certificate_order.managed_csrs << managed_csr
-
# end
-
#
-
# @certificate_order.managed_csrs << ManagedCsr.find_by_ref(params[:managed_csr]) if params[:managed_csr] != 'none'
-
# @certificate_order.managed_domains << Domain.where(id: params[:managed_domains]) if params[:managed_domains]
-
-
if params[:add_to_manager] == 'true' and !['none',nil].include? params[:managed_csr]
-
managed_csr = ManagedCsr.new
-
managed_csr.body = params[:certificate_order][:certificate_contents_attributes]['0'.to_sym][:signing_request]
-
managed_csr.friendly_name = managed_csr.common_name || managed_csr.sha1_hash
-
managed_csr.ssl_account_id = current_user.ssl_account.id
-
@certificate_order.managed_csrs << managed_csr unless
-
@certificate_order.managed_csrs.map(&:public_key_sha1).include? managed_csr.public_key_sha1
-
-
unless managed_csr.errors.blank?
-
flash[:error] = "Some error occurs while adding this csr to the csr manager."
-
@certificate = @certificate_order.certificate
-
-
format.html { render '/certificates/buy', :layout=>'application' }
-
end
-
-
@certificate_order.managed_csrs << managed_csr
-
end
-
end
-
-
def set_algorithm_and_size
-
@integrated_algorithm = [
-
['RSA', 'RSASSA-PKCS1-v1_5'],
-
['ECDSA', 'ECDSA']
-
]
-
-
# @hash_algorithm = [
-
# ['SHA-256', 'SHA-256'],
-
# ['SHA-384', 'SHA-384'],
-
# ['SHA-512', 'SHA-512']
-
# ]
-
-
@sign_algorithm = [
-
['RSASSA-PKCS1-v1_5', 'RSASSA-PKCS1-v1_5'],
-
['ECDSA', 'ECDSA'],
-
['RSA-PSS', 'RSA-PSS']
-
]
-
-
@rsa_key_size = [
-
['2048', '2048'],
-
['4096', '4096']
-
]
-
-
@ecc_key_size = [
-
['256', '256'],
-
['384', '384']
-
]
-
end
-
end
-
class CertificatesController < ApplicationController
-
before_filter :find_tier
-
before_filter :require_user, :only=>[:buy, :buy_renewal],
-
:if=>'request.subdomain==Reseller::SUBDOMAIN'
-
before_filter :require_user,
-
only: [:admin_index, :new, :edit, :create, :update, :manage_product_variants]
-
before_filter :find_certificate,
-
only: [:show, :buy, :pricing, :buy_renewal]
-
before_filter :find_certificate_by_id,
-
only: [:edit, :update, :manage_product_variants]
-
filter_access_to :edit, :update, :manage_product_variants,
-
attribute_check: true
-
filter_access_to :buy_renewal, :new, :admin_index, :create
-
layout false, only: [:pricing]
-
-
def index
-
@certificates =
-
if Rails.env.development?
-
@tier.blank? ? Certificate.root_products : Certificate.tiered_products(@tier)
-
else
-
Rails.cache.fetch(@tier.blank? ? "tier_nil" : "tier_#{@tier}", expires_in: 30.days) do
-
@tier.blank? ? Certificate.root_products : Certificate.tiered_products(@tier)
-
end
-
end
-
end
-
-
def single_domain
-
@certificates = Certificate.available
-
unless @tier.blank?
-
@certificates = @certificates.find_all{|c|
-
c.product=~Regexp.new(@tier) && c.is_single?}
-
else
-
@certificates = @certificates.reject{|c|
-
c.product=~/\dtr/ || c.is_multi?}
-
end
-
render :action=>'single_or_multi'
-
end
-
-
def wildcard_or_ucc
-
@certificates = Certificate.available
-
unless @tier.blank?
-
@certificates = @certificates.find_all{|c|
-
c.product=~Regexp.new(@tier) && c.is_multi?}
-
else
-
@certificates = @certificates.reject{|c|
-
c.product=~/\dtr/ || c.is_single?}
-
end
-
render :action=>'single_or_multi'
-
end
-
-
# GET /certificate/wildcard
-
# GET /certificate/wildcard.xml
-
def show
-
@certificates = Certificate.available
-
unless @tier.blank?
-
@certificates = @certificates.find_all{|c|
-
c.product=~Regexp.new(@tier)}
-
else
-
@certificates = @certificates.reject{|c|
-
c.product=~/\dtr/}
-
end
-
respond_to do |format|
-
unless @certificate.blank?
-
format.html { render :action => "show_"+@certificate.product_root}
-
format.xml { render :xml => @certificate}
-
else
-
format.html {not_found}
-
end
-
end
-
end
-
-
# GET /certificate/buy/wildcard
-
# GET /certificate/buy/wildcard.xml
-
def buy
-
prep_purchase
-
respond_to do |format|
-
unless @certificate.blank?
-
format.html { render action: :buy}
-
format.xml { render :xml => @certificate}
-
else
-
format.html {not_found}
-
end
-
end
-
end
-
-
def buy_renewal
-
buy
-
end
-
-
def get_certificates_list
-
@certificates = Certificate.available
-
unless @tier.blank?
-
@certificates = @certificates.find_all{|c|
-
c.product=~Regexp.new(@tier) && c.is_single?}
-
else
-
@certificates = @certificates.reject{|c|
-
c.product=~/\dtr/ || c.is_multi?}
-
end
-
end
-
-
def pricing
-
prep_purchase
-
@values=@certificate.pricing(@certificate_order, @certificate_content)
-
respond_to do |format|
-
unless @certificate.blank?
-
format.html { render :action => "pricing"}
-
format.js { render :action => "pricing"}
-
format.json { render :action => "pricing"}
-
format.xml { render :xml => @certificate}
-
else
-
format.html {not_found}
-
end
-
end
-
end
-
-
def new
-
@certificate = Certificate.new
-
end
-
-
def edit
-
end
-
-
def update
-
parse_params
-
if @certificate.update(@new_params)
-
update_cas_certificates
-
flash[:notice] = "Certificate #{@certificate.serial} was successfully updated."
-
log_system_audit(:update)
-
mpv_redirect_to_cert
-
else
-
render :edit,
-
error: "Failed to update certificate due to errors: #{@certificate.errors.full_messages.join(', ')}."
-
end
-
end
-
-
def create
-
parse_params
-
@certificate = Certificate.new(@new_params)
-
if @certificate.save
-
update_cas_certificates
-
flash[:notice] = "Certificate #{@certificate.serial} was successfully created."
-
log_system_audit(:create)
-
mpv_redirect_to_cert
-
else
-
render :new,
-
error: "Failed to create certificate due to errors: #{@certificate.errors.full_messages.join(', ')}."
-
end
-
end
-
-
def manage_product_variants
-
if @certificate
-
@pv_group = @certificate.product_variant_groups.find(params[:pvg]) if params[:pvg]
-
@pv_item = ProductVariantItem.find(params[:pvi]) if params[:pvi]
-
@pvi_params = params.dup.keep_if {|k,_| (ProductVariantItem.attribute_names - ['id']).include?(k)}
-
@pvg_params = params.dup.keep_if {|k,_| (ProductVariantGroup.attribute_names - ['id']).include?(k)}
-
-
case params[:manage_type]
-
when 'delete_group' then mpv_delete_group
-
when 'create_group' then mpv_create_group
-
when 'create_item' then mpv_create_item
-
when 'delete_item' then mpv_delete_item
-
when 'update_item' then mpv_update_item
-
when 'manage_items' then mpv_manage_items
-
else
-
mpv_redirect_to_cert
-
end
-
end
-
end
-
-
def admin_index
-
@certificates = Certificate.all.sort_with(params)
-
@certificates = @certificates.index_filter(params) if params[:commit]
-
@certificates = @certificates.paginate(page: params[:page], per_page: 25)
-
end
-
-
private
-
-
def mpv_delete_group
-
if @pv_group.destroy
-
flash[:notice] = "Group #{@pv_group.id} was successfully deleted."
-
else
-
flash[:error] = "Something went wrong while deleting group, please try again."
-
end
-
mpv_redirect_to_cert
-
end
-
-
def mpv_create_group
-
new_group = ProductVariantGroup.new(
-
@pvg_params.merge(variantable_id: @certificate.id, variantable_type: 'Certificate')
-
)
-
if new_group.save
-
flash[:notice] = "Group was successfully created."
-
else
-
flash[:error] = "Failed to create group due to errors: #{new_group.errors.full_messages.join(', ')}!"
-
end
-
mpv_redirect_to_cert
-
end
-
-
def mpv_create_item
-
new_item = ProductVariantItem.new(
-
@pvi_params.merge(product_variant_group_id: @pv_group.id)
-
)
-
if new_item.save
-
flash[:notice] = "Item #{new_item.serial} was successfully created."
-
else
-
flash[:error] = "Failed to create item due to errors: #{new_item.errors.full_messages.join(', ')}!"
-
end
-
mpv_redirect_to_group
-
end
-
-
def mpv_delete_item
-
if @pv_item && @pv_item.destroy
-
flash[:notice] = "Item #{@pv_item.serial} was successfully deleted."
-
else
-
flash[:error] = "Something went wrong, please try again."
-
end
-
mpv_redirect_to_group
-
end
-
-
def mpv_update_item
-
if @pv_item && @pv_item.update(@pvi_params)
-
flash[:notice] = "Item #{@pv_item.serial} was successfully updated."
-
else
-
error = if @pv_item
-
"Failed to update item #{@pv_item.serial} due to errors: #{@pv_item.errors.full_messages.join(', ')}!"
-
else
-
"Something went wrong, please try again."
-
end
-
flash[:error] = error
-
end
-
mpv_redirect_to_group
-
end
-
-
def mpv_manage_items
-
render :manage_product_variants
-
end
-
-
def mpv_redirect_to_group
-
redirect_to manage_product_variants_certificate_path(
-
@certificate.id, pvg: @pv_group, manage_type: 'manage_items'
-
)
-
end
-
-
def mpv_redirect_to_cert
-
redirect_to edit_certificate_path(@certificate.id)
-
end
-
-
def prep_purchase
-
unless @certificate.blank?
-
@certificate_order =
-
if params[:rekeying]
-
CertificateOrder.unscoped.find_by_ref(params[:rekeying])
-
else
-
CertificateOrder.new(:duration=>(params[:id]=='free') ? 1 : 2)
-
end
-
@certificate_order.ssl_account=current_user.ssl_account unless current_user.blank?
-
@certificate_order.has_csr=false #this is the single flag that hides/shows the csr prompt
-
domains = if instance_variable_get("@#{CertificateOrder::RENEWING}")
-
@certificate_order.renewal_id=instance_variable_get("@#{CertificateOrder::RENEWING}").id
-
instance_variable_get("@#{CertificateOrder::RENEWING}").certificate_content.all_domains
-
else
-
@certificate_order.certificate_content ? @certificate_order.certificate_content.all_domains : []
-
end
-
@certificate_content = CertificateContent.new(domains: domains)
-
end
-
end
-
-
def find_certificate_by_id
-
cur_id = params[:certificate] ? params[:certificate][:id] : params[:id]
-
@certificate = Certificate.includes(:product_variant_items).find cur_id
-
end
-
-
def parse_params
-
cert = params[:certificate]
-
@new_params = cert
-
.merge(display_order: JSON.parse(cert[:display_order]))
-
.merge(description: JSON.parse(cert[:description])).to_h
-
end
-
-
def update_cas_certificates
-
cas = params[:ca_certificates]
-
if cas && cas.any?
-
@certificate.cas_certificates.where.not(ca_id: cas).destroy_all
-
exist_cas = @certificate.cas_certificates.where(ca_id: cas).map(&:ca)
-
@certificate.cas << (Ca.where(id: cas) - exist_cas)
-
else
-
@certificate.cas_certificates.destroy_all
-
end
-
end
-
-
def log_system_audit(type)
-
action = type == :create ? 'created' : 'updated'
-
SystemAudit.create(
-
owner: current_user,
-
target: @certificate,
-
action: "User #{current_user.email} has #{action} certificate on #{DateTime.now.strftime("%b %d, %Y %R %Z")}",
-
notes: "Certificate #{@certificate.serial} #{action.capitalize}"
-
)
-
end
-
end
-
require 'active_support/concern'
-
-
module SerializerHelper
-
extend ActiveSupport::Concern
-
-
def serialize_model(model, options = {})
-
options[:namespace] = Api::V1
-
options[:is_collection] = false
-
serialize_resource(model, options)
-
end
-
-
def serialize_models(models, options = {})
-
options[:namespace] = Api::V1
-
options[:is_collection] = true
-
serialize_resource(models, options)
-
end
-
-
def serialize_object_errors(object)
-
JSONAPI::Serializer.serialize_errors(object.errors)
-
end
-
-
def serialize_resource(resource, options)
-
JSONAPI::Serializer.serialize(resource, options)
-
end
-
end
-
class ContactsController < ApplicationController
-
layout 'application'
-
-
before_filter :find_ssl_account, only: :saved_contacts
-
before_filter :find_contact, only: [:admin_update, :edit, :update, :destroy]
-
-
filter_access_to :all
-
filter_access_to :edit, :update, :show, :destroy, attribute_check: true
-
-
def index
-
@certificate_content =
-
(current_user.is_system_admins? ? CertificateContent :
-
current_user.ssl_account.certificate_contents).find params[:certificate_content_id]
-
@certificate_order = @certificate_content.certificate_order
-
@saved_contacts = @certificate_order.ssl_account.saved_contacts
-
respond_to do |format|
-
format.html
-
format.xml { render :xml => @contacts }
-
end
-
end
-
-
def saved_contacts
-
if current_user
-
@registrants = params[:registrants] == 'true'
-
@all_contacts = @registrants ? get_saved_registrants : get_saved_contacts
-
@all_contacts = @all_contacts.index_filter(params) if params[:commit]
-
@all_contacts = @all_contacts.order(:last_name)
-
.paginate(page: params[:page], per_page: 25)
-
end
-
respond_to :html
-
end
-
-
def enterprise_pki_service_agreement
-
filename = "SSLcom Enterprise PKI Service Agreement 1.0.pdf"
-
send_file File.join("public", "agreements", "enterprise_pki_agreement_1.0.pdf"),
-
type: "application/pdf", filename: filename, disposition: 'inline'
-
end
-
-
def show
-
if params[:saved_contact]
-
find_contact
-
else
-
@certificate_content = CertificateContent.find params[:certificate_content_id]
-
@certificate_order = @certificate_content.certificate_order
-
end
-
respond_to do |format|
-
format.html
-
format.xml { render :xml => @contact }
-
end
-
end
-
-
def new
-
if params[:saved_contact]
-
@contact = Contact.new
-
respond_to :html
-
else
-
@certificate_content = CertificateContent.find params[:certificate_content_id]
-
@certificate_order = @certificate_content.certificate_order
-
respond_to do |format|
-
format.html
-
format.xml { render :xml => @contact }
-
end
-
end
-
end
-
-
def edit
-
@render_epki_registrant = @contact.show_domains?
-
end
-
-
def create
-
if params[:contact][:epki_registrant]
-
create_epki_registrant
-
else
-
registrant = params[:contact][:type]=='Registrant'
-
new_params = set_registrant_type(params).merge(
-
contactable_id: current_user.ssl_account.id,
-
contactable_type: 'SslAccount'
-
)
-
@contact = registrant ? Registrant.new(new_params) : CertificateContact.new(new_params)
-
if @contact.save
-
flash[:notice] = "Contact was successfully created."
-
redirect_to_index
-
else
-
@contact = @contact.becomes(Contact)
-
render :new
-
end
-
end
-
end
-
-
def admin_update
-
if @contact && params[:status]
-
previous_status = @contact.status
-
@contact.update_column(:status, Contact.statuses[params[:status]])
-
SystemAudit.create(
-
owner: current_user,
-
target: @contact,
-
notes: "Saved Identity #{@contact.email} status was updated from
-
'#{previous_status}' to '#{@contact.status}' by #{current_user.email}.",
-
action: "Saved Identity #{@contact.email} status update."
-
)
-
validate_certificate_orders
-
end
-
notice_ext = @co_validated && @co_validated > 0 ? "And #{@co_validated} certificate order(s) were validated." : ""
-
flash[:notice] = "Status has been successfully updated for #{@contact.company_name}. #{notice_ext}"
-
redirect_to_index
-
end
-
-
def update
-
epki_registrant = params[:contact][:epki_registrant]
-
new_params = if epki_registrant
-
get_epki_registrant_params
-
else
-
@contact.contact_iv? ? set_iv_type : set_registrant_type(params)
-
end
-
-
respond_to do |format|
-
@render_epki_registrant = @contact.show_domains?
-
-
type = if @contact.contact_iv?
-
IndividualValidation
-
else
-
new_params[:type] == 'CertificateContact' ? CertificateContact : Registrant
-
end
-
-
if @contact.becomes(type).update_attributes(new_params)
-
flash[:notice] = "#{@contact.type} was successfully updated."
-
update_epki_registrant
-
format.html { redirect_to_index }
-
format.json { render json: @contact, status: :ok }
-
else
-
format.html { render :edit }
-
format.json { render json: @contact.errors, status: :unprocessable_entity }
-
end
-
end
-
end
-
-
def destroy
-
if @contact.destroy
-
flash[:notice] = "Contact was successfully deleted."
-
redirect_to_index
-
end
-
end
-
-
private
-
-
def get_epki_registrant_params
-
domains = params[:contact][:domains].strip.split(/[\s,]+/).map(&:strip)
-
new_params = set_registrant_type(params).merge(
-
contactable_id: current_user.ssl_account.id,
-
contactable_type: "SslAccount",
-
status: Contact::statuses[:pending_epki],
-
registrant_type: Registrant::registrant_types[:organization],
-
type: "Registrant",
-
domains: domains
-
)
-
new_params.delete("epki_registrant")
-
new_params
-
end
-
-
def update_epki_registrant
-
if @render_epki_registrant
-
flash[:notice] = "EPKI Agreement was successfully updated. Please wait for SSL.com Administrator to approve this identity."
-
team_name = current_user.ssl_account.get_team_name
-
SystemAudit.create(
-
owner: current_user,
-
target: @contact,
-
action: "Existing EPKI Agreement update request for #{team_name}",
-
notes: "User #{current_user.email} has requested changes to existing EPKI Registrant for team #{team_name}."
-
)
-
end
-
end
-
-
def create_epki_registrant
-
new_params = get_epki_registrant_params
-
@contact = Registrant.new(new_params)
-
if @contact.save
-
flash[:notice] = "EPKI Agreement was successfully created. Please wait for SSL.com Administrator to approve this identity."
-
team_name = current_user.ssl_account.get_team_name
-
SystemAudit.create(
-
owner: current_user,
-
target: @contact,
-
action: "New EPKI Agreement Request for #{team_name}",
-
notes: "User #{current_user.email} has requested new EPKI Registrant for team #{team_name}."
-
)
-
redirect_to_index
-
else
-
@render_epki_registrant = true
-
@contact = @contact.becomes(Contact)
-
render :new
-
end
-
end
-
-
def redirect_to_index
-
redirect_to saved_contacts_contacts_path(
-
@contact.contactable.to_slug,
-
registrants: (@contact.contact_ov? || @contact.contact_iv? ? true : nil)
-
)
-
end
-
-
def get_saved_contacts
-
if current_user.is_system_admins?
-
Contact.where(contactable_type: 'SslAccount', type: 'CertificateContact')
-
else
-
@ssl_account.saved_contacts
-
end
-
end
-
-
def get_saved_registrants
-
if current_user.is_system_admins?
-
Contact.where(contactable_type: 'SslAccount', type: ['Registrant', 'IndividualValidation'])
-
else
-
@ssl_account.saved_registrants
-
end
-
end
-
-
def validate_certificate_orders
-
# Update certificate order validation status if registrant was used in
-
# any client or s/mime certificate order
-
if @contact.is_a?(Registrant) && params[:status] == 'validated'
-
contacts = Contact.where(parent_id: @contact.id)
-
if contacts
-
@co_validated = 0
-
CertificateOrder.joins(certificate_contents: :locked_registrant)
-
.where("contacts.id IN (?)", contacts.ids).each do |co|
-
if co.certificate.is_smime_or_client? && co.locked_registrant
-
co.locked_registrant.validated!
-
co.registrant.validated!
-
if co.iv_ov_validated?
-
cc = co.certificate_content
-
unless cc.validated?
-
cc.validate!
-
@co_validated += 1
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
-
def find_contact
-
if current_user
-
@contact = if current_user.is_system_admins?
-
Contact.find_by(id: params[:id])
-
else
-
@contact = current_user.ssl_account.all_saved_contacts.find_by(id: params[:id])
-
end
-
end
-
end
-
-
def set_iv_type
-
contact = params[:contact]
-
contact[:registrant_type] = nil
-
contact[:type] = 'IndividualValidation'
-
contact
-
end
-
-
def set_registrant_type(params)
-
contact = params[:contact]
-
contact[:registrant_type] = nil if (contact[:type] == 'CertificateContact')
-
unless contact[:registrant_type].blank?
-
contact = contact.merge(
-
registrant_type: Registrant::registrant_types.key(contact[:registrant_type].to_i)
-
)
-
end
-
contact
-
end
-
end
-
class CsrsController < ApplicationController
-
before_filter :find_csr, only:[:http_dcv_file, :verification_check, :create_new_unique_value]
-
filter_access_to :all, :attribute_check=>true, except: [:verification_check]
-
filter_access_to :country_codes, :http_dcv_file, :all_domains, :check_validation, :create_new_unique_value, :require=>[:create] #anyone can create read creates csrs, thus read this
-
-
# PUT /csrs/1
-
# PUT /csrs/1.xml
-
def update
-
respond_to do |format|
-
if @csr.update_attributes(params[:csr])
-
@csr.certificate_content.tap do |cc|
-
cc.update_attribute(:workflow_state, "contacts_provided") if cc.pending_validation?
-
end
-
format.html {
-
flash[:notice] = 'Csr was successfully updated.'
-
redirect_to(@csr.certificate_content.certificate_order) }
-
format.xml { head :ok }
-
format.js { render :json=>@csr.to_json(:include=>:signed_certificate)}
-
else
-
format.html { render :action => "edit" }
-
format.xml { render :xml => @csr.errors, :status => :unprocessable_entity }
-
format.js { render :json=>@csr.errors.to_json}
-
end
-
end
-
end
-
-
def http_dcv_file
-
tmp_file="#{Rails.root}/tmp/#{@csr.md5_hash}.txt"
-
File.open(tmp_file, 'wb') do |f|
-
f.write @csr.dcv_contents
-
end
-
send_file tmp_file, :type => 'text', :disposition => 'attachment',
-
:filename =>@csr.md5_hash+".txt"
-
end
-
-
def verification_check
-
http_or_s = false
-
-
if params[:ref]
-
if cc = CertificateContent.find_by_ref(params[:ref])
-
cn = cc.certificate_names.find_by_name(params[:dcv].split(':')[1])
-
-
if cn
-
cn.new_name params['new_name']
-
http_or_s = cn.dcv_verify(params[:protocol])
-
-
if http_or_s.to_s == 'true'
-
dcv = cn.domain_control_validations.last
-
if dcv && (dcv.dcv_method == params[:protocol])
-
dcv.satisfy! unless dcv.satisfied?
-
else
-
dcv=cn.domain_control_validations.create(
-
dcv_method: params[:protocol],
-
candidate_addresses: nil,
-
failure_action: 'ignore')
-
dcv.satisfy!
-
end
-
elsif http_or_s.nil?
-
http_or_s = false
-
end
-
end
-
end
-
else
-
cn = CertificateName.includes(:domain_control_validations).find_by_id(params[:choose_cn])
-
csr = Csr.find_by_id(params[:selected_csr])
-
-
http_or_s = CertificateName.dcv_verify(protocol: params[:protocol],
-
https_dcv_url: "https://#{cn.name}/.well-known/pki-validation/#{csr.md5_hash}.txt",
-
http_dcv_url: "http://#{cn.name}/.well-known/pki-validation/#{csr.md5_hash}.txt",
-
cname_origin: "#{csr.dns_md5_hash}.#{cn.name}",
-
cname_destination: "#{csr.cname_destination}",
-
csr: csr,
-
ca_tag: csr.ca_tag)
-
-
if http_or_s.to_s == 'true'
-
dcv = cn.domain_control_validations.last
-
-
if dcv && (dcv.dcv_method == params[:protocol])
-
dcv.satisfy! unless dcv.satisfied?
-
else
-
dcv=csr.domain_control_validations.create(
-
dcv_method: params[:protocol],
-
candidate_addresses: nil,
-
failure_action: 'ignore')
-
dcv.satisfy!
-
end
-
elsif http_or_s.nil?
-
http_or_s = false
-
end
-
end
-
-
# http_or_s=ActiveRecord::Base.find_from_model_and_id(params[:dcv]).dcv_verify(params[:protocol])
-
respond_to do |format|
-
format.html { render inline: http_or_s.to_s }
-
end
-
end
-
-
def all_domains
-
returnObj = {}
-
selected_csr = Csr.find_by_ref(params[:ref])
-
returnObj['common_name'] = selected_csr.common_name
-
returnObj['subject_alternative_names'] = selected_csr.subject_alternative_names
-
returnObj['csr_body'] = selected_csr.body
-
returnObj['days_left'] = selected_csr.days_left
-
returnObj['public_key_sha1'] = selected_csr.public_key_sha1
-
-
render :json => returnObj
-
end
-
-
def check_validation
-
domains = params[:domains]
-
public_key_sha1 = params[:public_key_sha1] || ''
-
returnObj = {}
-
-
domains.each do |domain|
-
exist_validated = false
-
-
CertificateName.find_by_domains(domain).each do |name|
-
last_dcv = name.domain_control_validations.last
-
-
if last_dcv && last_dcv.satisfied?
-
if last_dcv.dcv_method == 'email'
-
exist_validated = true
-
break
-
elsif last_dcv.csr && (last_dcv.cached_csr_public_key_sha1 == public_key_sha1)
-
exist_validated = true
-
break
-
end
-
end
-
end
-
-
returnObj[domain] = exist_validated ? 'true' : 'false'
-
end
-
-
render :json => returnObj
-
end
-
-
def create_new_unique_value
-
returnObj = {}
-
same_exist = @csr.csr_unique_values.where(unique_value: params[:new_unique_value]).first
-
-
if same_exist
-
returnObj['same'] = true
-
else
-
@csr.csr_unique_values.create(unique_value: params[:new_unique_value])
-
-
returnObj['cname_destination'] = @csr.cname_destination
-
returnObj['dns_sha2_hash'] = @csr.dns_sha2_hash
-
end
-
-
-
render :json => returnObj
-
end
-
-
private
-
-
def find_csr
-
@csr=Csr.find(params[:id])
-
end
-
end
-
-
class DomainsController < ApplicationController
-
before_filter :require_user, :except => [:dcv_validate, :dcv_all_validate]
-
before_filter :find_ssl_account
-
before_filter :set_row_page, only: [:index, :search]
-
before_filter :set_csr_row_page, only: [:select_csr]
-
-
def search
-
index
-
end
-
-
def index
-
@search = params[:search] || ""
-
-
if @search.blank?
-
cnames = @ssl_account.all_certificate_names.includes(:domain_control_validations,:signed_certificates).order(created_at: :desc)
-
total_domains = (@ssl_account.domains.order(created_at: :desc) + cnames).uniq(&:id)
-
else
-
cnames = @ssl_account.all_certificate_names.includes(:domain_control_validations,:signed_certificates).search_domains(params[:search])
-
domains = @ssl_account.domains.search_domains(params[:search])
-
total_domains = (domains + cnames).uniq(&:id)
-
end
-
-
@domains = total_domains.uniq{|cn| [cn.name, cn.certificate_content_id, cn.ssl_account_id]}.paginate(@p)
-
-
respond_to do |format|
-
format.html { render :action => :index }
-
format.xml { render :xml => @domains }
-
end
-
end
-
-
def create
-
res_Obj = {}
-
exist_domain_names = []
-
created_domains = []
-
created_domain_validated_status = {}
-
validated_domains_remains = {}
-
-
unless params[:domain_names].nil?
-
domain_names = params[:domain_names].split(/[\s,']/)
-
domain_names.each do |d_name|
-
next if d_name.empty?
-
-
if @ssl_account.domains.map(&:name).include?(d_name)
-
exist_domain_names << d_name
-
else
-
@domain = Domain.new
-
@domain.name = d_name
-
@domain.ssl_account_id = @ssl_account.id
-
@domain.save()
-
current_user.ssl_account.other_dcvs_satisfy_domain(@domain)
-
created_domains << @domain
-
-
dcv = @domain.domain_control_validations.last
-
created_domain_validated_status[d_name] = dcv && dcv.satisfied? ? 'true' : 'false'
-
-
validated_domains_remains[d_name] = dcv && dcv.responded_at ?
-
DomainControlValidation::MAX_DURATION_DAYS[:email] - (Date.today - dcv.responded_at.to_date).to_i :
-
0
-
end
-
end
-
end
-
res_Obj['domains'] = created_domains
-
res_Obj['domains_status'] = created_domain_validated_status
-
res_Obj['remain_days'] = validated_domains_remains
-
res_Obj['exist_domains'] = exist_domain_names
-
render :json => res_Obj
-
end
-
-
def destroy
-
@domain = current_user.ssl_account.domains.find_by(id: params[:id])
-
@domain = current_user.ssl_account.all_certificate_names.find_by(id: params[:id]) if @domain.nil?
-
@domain.destroy
-
respond_to do |format|
-
flash[:notice] = "Domain was successfully deleted."
-
format.html { redirect_to domains_path(@ssl_slug) }
-
end
-
end
-
-
def validation_request
-
@domain = current_user.ssl_account.domains.find_by(id: params[:id])
-
if @domain.domain_control_validations.last.try(:identifier_found)
-
redirect_to domains_path(@ssl_slug)
-
return
-
end
-
@addresses = CertificateName.candidate_email_addresses(@domain.non_wildcard_name)
-
if params[:authenticity_token]
-
if params[:dcv_address]=~EmailValidator::EMAIL_FORMAT
-
if DomainControlValidation.approved_email_address? CertificateName.candidate_email_addresses(
-
@domain.non_wildcard_name), params[:dcv_address]
-
identifier = (SecureRandom.hex(8)+Time.now.to_i.to_s(32))[0..19]
-
@domain.domain_control_validations.create(dcv_method: "email", email_address: params[:dcv_address],
-
identifier: identifier, failure_action: "ignore", candidate_addresses: @addresses)
-
OrderNotifier.dcv_email_send(nil, params[:dcv_address], identifier, [@domain.name], @domain.id, @ssl_slug, 'team').deliver
-
@domain.domain_control_validations.last.send_dcv!
-
flash[:notice] = "Validation email has been sent."
-
else
-
flash[:notice] = "Invalid recipient email address."
-
end
-
end
-
end
-
end
-
-
def validate_all
-
if params[:authenticity_token]
-
send_validation_email(params)
-
end
-
@all_domains = []
-
@address_choices = []
-
@cnames = @ssl_account.all_certificate_names(nil,"unvalidated").
-
includes(:domain_control_validations).order(created_at: :desc)
-
@cnames.each do |cn|
-
dcv = cn.domain_control_validations.last
-
next if dcv && dcv.identifier_found
-
@all_domains << cn
-
@address_choices << CertificateName.candidate_email_addresses(cn.non_wildcard_name)
-
end
-
@domains = @ssl_account.domains(nil,"unvalidated").includes(:domain_control_validations).order(created_at: :desc)
-
@domains.each do |dn|
-
dcv = dn.domain_control_validations.last
-
next if dcv && dcv.identifier_found
-
@all_domains << dn
-
@address_choices << CertificateName.candidate_email_addresses(dn.non_wildcard_name)
-
end
-
end
-
-
def remove_selected
-
res_Obj = {}
-
deleted_domains = []
-
params[:d_name_check].each do |d_name_id|
-
deleted_domains << d_name_id
-
d_name = CertificateName.find_by_id(d_name_id)
-
d_name.destroy
-
end
-
res_Obj['deleted_domains'] = deleted_domains
-
render :json => res_Obj
-
end
-
-
def validate_selected
-
if params[:d_name_id]
-
is_sent = send_validation_email(params)
-
-
if is_sent
-
flash[:notice] = "Please check your email for the validation code and submit it below to complete validation."
-
else
-
flash[:error] = "Please select a valid email address."
-
end
-
-
@validation_url = dcv_all_validate_domains_url(params)
-
redirect_to dcv_all_validate_domains_url(ssl_slug: current_user.ssl_account.ssl_slug)
-
else
-
@all_domains = []
-
@address_choices = []
-
@domain_details = {}
-
params[:d_name_check].each do |dn_name_id|
-
dn = CertificateName.find_by_id(dn_name_id)
-
dcv = dn.domain_control_validations.last
-
next if dcv && dcv.identifier_found
-
@all_domains << dn
-
@address_choices << CertificateName.candidate_email_addresses(dn.non_wildcard_name)
-
-
@domain_details[dn.name] = {}
-
@domain_details[dn.name]['dcv_method'] = dcv ? dcv.email_address : ''
-
@domain_details[dn.name]['prev_attempt'] = dcv ? dcv.email_address : 'validation not performed yet'
-
@domain_details[dn.name]['attempted_on'] = dcv ? dcv.created_at.strftime('%Y-%m-%d %H:%M:%S') : 'n/a'
-
@domain_details[dn.name]['status'] = dcv ? 'pending' : 'waiting'
-
end unless params[:d_name_check].blank?
-
end
-
end
-
-
def select_csr
-
if params[:d_name_check]
-
@selected_domains = []
-
params[:d_name_check].each do |d_id|
-
dn = CertificateName.find_by_id(d_id)
-
@selected_domains << dn
-
end
-
if @selected_domains.blank?
-
redirect_to domains_path(@ssl_slug)
-
end
-
@csrs = current_user.ssl_account.all_csrs.paginate(@p)
-
else
-
redirect_to domains_path(@ssl_slug)
-
end
-
end
-
-
def validate_against_csr
-
if params[:authenticity_token] && params[:d_name_selected]
-
@selected_domains = []
-
@address_choices = []
-
@domain_details = {}
-
params[:d_name_selected].each do |d_id|
-
dn = CertificateName.find_by_id(d_id)
-
@selected_domains << dn
-
if @selected_domains.blank?
-
redirect_to domains_path(@ssl_slug)
-
end
-
@address_choices << CertificateName.candidate_email_addresses(dn.non_wildcard_name)
-
-
@domain_details[dn.name] = {}
-
dcv_last = dn.domain_control_validations.last
-
@domain_details[dn.name]['dcv_method'] = dcv_last ?
-
(dcv_last.email_address ?
-
dcv_last.email_address
-
: dcv_last.dcv_method)
-
: ''
-
@domain_details[dn.name]['prev_attempt'] = dcv_last ?
-
(dcv_last.satisfied? ?
-
'validated' :
-
(dcv_last.email_address ?
-
dcv_last.email_address
-
: dcv_last.dcv_method))
-
: 'validation not performed yet'
-
@domain_details[dn.name]['attempted_on'] = dcv_last ? dcv_last.created_at : 'n/a'
-
@domain_details[dn.name]['status'] = dcv_last ? (dcv_last.satisfied? ? 'satisfied' : 'pending') : 'waiting'
-
end
-
@csr = Csr.find_by_id(params[:selected_csr])
-
if @csr.blank?
-
redirect_to domains_path(@ssl_slug)
-
end
-
dcvs = @csr.csr_unique_value.domain_control_validations
-
dcvs.each do |dcv|
-
next if dcv.workflow_state == 'satisfied'
-
dn = CertificateName.find_by_id(dcv.certificate_name_id)
-
next if @selected_domains.include?(dn)
-
@selected_domains << dn
-
@address_choices << CertificateName.candidate_email_addresses(dn.non_wildcard_name)
-
-
@domain_details[dn.name] = {}
-
dcv_last = dn.domain_control_validations.last
-
@domain_details[dn.name]['dcv_method'] = dcv_last ?
-
(dcv_last.email_address ?
-
dcv_last.email_address
-
: dcv_last.dcv_method)
-
: ''
-
@domain_details[dn.name]['prev_attempt'] = dcv_last ?
-
(dcv_last.satisfied? ?
-
'validated' :
-
(dcv_last.email_address ?
-
dcv_last.email_address
-
: dcv_last.dcv_method))
-
: 'validation not performed yet'
-
@domain_details[dn.name]['attempted_on'] = dcv_last ? dcv_last.created_at.strftime('%Y-%m-%d %H:%M:%S') : 'n/a'
-
@domain_details[dn.name]['status'] = dcv_last ? (dcv_last.satisfied? ? 'satisfied' : 'pending') : 'waiting'
-
end
-
elsif !params[:authenticity_token] && params[:unique_value]
-
csr_unique_value = CsrUniqueValue.find_by_unique_value(params[:unique_value])
-
@csr = csr_unique_value.csr
-
dcvs = csr_unique_value.domain_control_validations
-
-
@selected_domains = []
-
@address_choices = []
-
@domain_details = {}
-
-
dcvs.each do |dcv|
-
next if dcv.workflow_state == 'satisfied'
-
dn = CertificateName.find_by_id(dcv.certificate_name_id)
-
next if @selected_domains.include?(dn)
-
@selected_domains << dn
-
@address_choices << CertificateName.candidate_email_addresses(dn.non_wildcard_name)
-
-
@domain_details[dn.name] = {}
-
dcv_last = dn.domain_control_validations.last
-
@domain_details[dn.name]['dcv_method'] = dcv_last ?
-
(dcv_last.email_address ?
-
dcv_last.email_address
-
: dcv_last.dcv_method)
-
: ''
-
@domain_details[dn.name]['prev_attempt'] = dcv_last ?
-
(dcv_last.satisfied? ?
-
'validated' :
-
(dcv_last.email_address ?
-
dcv_last.email_address
-
: dcv_last.dcv_method))
-
: 'validation not performed yet'
-
@domain_details[dn.name]['attempted_on'] = dcv_last ? dcv_last.created_at.strftime('%Y-%m-%d %H:%M:%S') : 'n/a'
-
@domain_details[dn.name]['status'] = dcv_last ? (dcv_last.satisfied? ? 'satisfied' : 'pending') : 'waiting'
-
end
-
if @selected_domains.blank?
-
redirect_to domains_path(@ssl_slug)
-
end
-
else
-
d_name_ids = params[:d_name_id]
-
addresses = params[:dcv_address]
-
@selected_domains = []
-
@address_choices = []
-
@domain_details = {}
-
@csr = Csr.find_by_id(params[:selected_csr])
-
cnames = []
-
d_name_ids.each_with_index do |id, index|
-
cn = CertificateName.find_by_id(id)
-
@selected_domains << cn
-
@address_choices << CertificateName.candidate_email_addresses(cn.non_wildcard_name)
-
if addresses[index]=~EmailValidator::EMAIL_FORMAT
-
cn.domain_control_validations.create(dcv_method: "email", email_address: addresses[index],
-
candidate_addresses: @address_choices, csr_unique_value_id:
-
@csr.csr_unique_value.id) if @address_choices.include?(addresses[index])
-
elsif addresses[index] == 'http_csr_hash'
-
cn.domain_control_validations.create(dcv_method: "http_csr_hash", failure_action: "ignore", csr_unique_value_id: @csr.csr_unique_value.id)
-
elsif addresses[index] == 'https_csr_hash'
-
cn.domain_control_validations.create(dcv_method: "https_csr_hash", failure_action: "ignore", csr_unique_value_id: @csr.csr_unique_value.id)
-
elsif addresses[index] == 'cname_csr_hash'
-
cn.domain_control_validations.create(dcv_method: "cname_csr_hash", failure_action: "ignore", csr_unique_value_id: @csr.csr_unique_value.id)
-
else
-
next
-
end
-
cnames << cn
-
end unless d_name_ids.blank?
-
email_for_identifier = ''
-
identifier = ''
-
email_list = []
-
identifier_list = []
-
domain_ary = []
-
domain_list = []
-
emailed_domains = []
-
succeeded_domains = []
-
failed_domains = []
-
cnames.each do |cn|
-
dcv = cn.domain_control_validations.last
-
if dcv.dcv_method == 'email'
-
if DomainControlValidation.approved_email_address? CertificateName.candidate_email_addresses(
-
cn.non_wildcard_name), dcv.email_address
-
if dcv.email_address != email_for_identifier
-
if domain_list.length>0
-
domain_ary << domain_list
-
email_list << email_for_identifier
-
identifier_list << identifier
-
domain_list = []
-
end
-
identifier = (SecureRandom.hex(8)+Time.now.to_i.to_s(32))[0..19]
-
email_for_identifier = dcv.email_address
-
end
-
domain_list << cn.name
-
emailed_domains << cn.name
-
dcv.update_attribute(:identifier, identifier)
-
dcv.send_dcv! unless dcv.satisfied?
-
end
-
else
-
if dcv_verify(dcv.dcv_method, cn.name, @csr)
-
succeeded_domains << cn.name
-
dcv.satisfy! unless dcv.satisfied?
-
else
-
failed_domains << cn.name
-
end
-
end
-
-
@domain_details[cn.name] = {}
-
@domain_details[cn.name]['dcv_method'] = dcv ?
-
(dcv.email_address ?
-
dcv.email_address
-
: dcv.dcv_method)
-
: ''
-
@domain_details[cn.name]['prev_attempt'] = dcv ?
-
(dcv.satisfied? ?
-
'validated' :
-
(dcv.email_address ?
-
dcv.email_address
-
: dcv.dcv_method))
-
: 'validation not performed yet'
-
@domain_details[cn.name]['attempted_on'] = dcv ? dcv.created_at.strftime('%Y-%m-%d %H:%M:%S') : 'n/a'
-
@domain_details[cn.name]['status'] = dcv ? (dcv.satisfied? ? 'satisfied' : 'pending') : 'waiting'
-
end
-
domain_ary << domain_list
-
email_list << email_for_identifier
-
identifier_list << identifier
-
unless domain_list.blank?
-
email_list.each_with_index do |value, key|
-
OrderNotifier.dcv_email_send(nil, value, identifier_list[key], domain_ary[key], nil, @ssl_slug, 'group').deliver
-
end
-
end
-
notice_string = ""
-
unless succeeded_domains.blank?
-
notice_string += "Domain Control Validation for #{succeeded_domains.join(", ")} succeeded. "
-
end
-
unless failed_domains.blank?
-
notice_string += "Domain Control Validation for #{failed_domains.join(", ")} failed. "
-
end
-
unless emailed_domains.blank?
-
notice_string += "Domain Control Validation email for #{emailed_domains.join(", ")} sent. "
-
end
-
flash[:notice] = notice_string
-
end
-
end
-
-
def dcv_verify(protocol, domain_name, csr)
-
CertificateName.dcv_verify(protocol: protocol,
-
https_dcv_url: "https://#{domain_name}/.well-known/pki-validation/#{csr.md5_hash}.txt",
-
http_dcv_url: "http://#{domain_name}/.well-known/pki-validation/#{csr.md5_hash}.txt",
-
cname_origin: "#{csr.dns_md5_hash}.#{domain_name}",
-
cname_destination: "#{csr.cname_destination}",
-
csr: csr,
-
ca_tag: csr.ca_tag)
-
end
-
-
def dcv_validate
-
@domain = current_user.ssl_account.domains.includes(:domain_control_validations).find_by(id: params[:id]) ||
-
current_user.ssl_account.all_certificate_names.includes(:domain_control_validations).find_by(id: params[:id]) if @domain.nil?
-
if(params['authenticity_token'])
-
identifier = params['validate_code']
-
dcv = @domain.domain_control_validations.last
-
if dcv.identifier == identifier
-
dcv.update_attribute(:identifier_found, true)
-
unless dcv.satisfied?
-
dcv.satisfy!
-
# CaaCheck.pass?(@ssl_account.acct_number + 'domains', @domain, nil)
-
end
-
end
-
end
-
end
-
-
# TODO rewrite this so we extract only certificate_names with no satisfied domain_control_validations
-
def dcv_all_validate
-
validated=[]
-
# directly scoped to the team
-
dnames = @ssl_account.domains.includes(:domain_control_validations)
-
# scoped to certificate_orders
-
cnames = @ssl_account.all_certificate_names.includes(:domain_control_validations)
-
if(params['authenticity_token'])
-
identifier = params['validate_code']
-
(dnames+cnames).each do |cn|
-
dcv = cn.domain_control_validations.last
-
if dcv && dcv.identifier == identifier && dcv.responded_at.blank?
-
# dcv.update_columns(identifier_found: true, responded_at: DateTime.now)
-
validated << cn.name
-
unless dcv.satisfied?
-
dcv.satisfy!
-
end
-
# find similar order scope domain (or create a new team scoped domain) and validate it
-
team_domain=@ssl_account.domains.where.not(certificate_content_id: nil).find_by_name(cn.name) ||
-
@ssl_account.domains.create(cn.attributes.except("id","certificate_content_id"))
-
team_domain.domain_control_validations.create(dcv.attributes.except("id")) if
-
team_domain.domain_control_validations.empty? or
-
!team_domain.domain_control_validations.last.satisfied?
-
# find all other non validated certificate_names and validate them
-
validated<<@ssl_account.satisfy_related_dcvs(cn)
-
cn.certificate_content.certificate_order.apply_for_certificate if cn.certificate_content
-
end
-
end
-
unless validated.empty?
-
flash[:notice] = "The following domains are now validated: #{validated.flatten.uniq.join(" ,")}"
-
redirect_to(domains_path) if current_user
-
else
-
flash.now[:error] = "No domains have been validated."
-
end
-
end
-
end
-
-
private
-
-
def send_validation_email(params)
-
d_name_ids = params[:d_name_id]
-
addresses = params[:dcv_address]
-
cnames = []
-
d_name_ids.each_with_index do |id, index|
-
if addresses[index] =~ EmailValidator::EMAIL_FORMAT
-
cn = CertificateName.find_by_id(id)
-
cn.domain_control_validations.create(dcv_method: "email", email_address: addresses[index],
-
candidate_addresses: CertificateName.candidate_email_addresses(cn.non_wildcard_name))
-
cnames << cn
-
end
-
end
-
email_for_identifier = ''
-
identifier = ''
-
email_list = []
-
identifier_list = []
-
domain_ary = []
-
domain_list = []
-
cnames.each do |cn|
-
dcv = cn.domain_control_validations.last
-
if DomainControlValidation.approved_email_address? CertificateName.candidate_email_addresses(
-
cn.non_wildcard_name), dcv.email_address
-
if dcv.email_address != email_for_identifier
-
if domain_list.length > 0
-
domain_ary << domain_list
-
email_list << email_for_identifier
-
identifier_list << identifier
-
domain_list = []
-
end
-
identifier = (SecureRandom.hex(8) + Time.now.to_i.to_s(32))[0..19]
-
email_for_identifier = dcv.email_address
-
end
-
domain_list << cn.name
-
dcv.update_attribute(:identifier, identifier)
-
dcv.send_dcv!
-
end
-
end
-
domain_ary << domain_list
-
email_list << email_for_identifier
-
identifier_list << identifier
-
-
if email_list[0] != ''
-
email_list.each_with_index do |value, key|
-
OrderNotifier.dcv_email_send(nil, value, identifier_list[key], domain_ary[key], nil, @ssl_slug, 'group').deliver
-
end
-
-
return true
-
else
-
return false
-
end
-
end
-
-
def set_row_page
-
preferred_row_count = current_user.preferred_domain_row_count
-
@per_page = params[:per_page] || preferred_row_count.or_else("10")
-
Domain.per_page = @per_page if Domain.per_page != @per_page
-
-
if @per_page != preferred_row_count
-
current_user.preferred_domain_row_count = @per_page
-
current_user.save(validate: false)
-
end
-
-
@p = {page: (params[:page] || 1), per_page: @per_page}
-
end
-
-
def set_csr_row_page
-
preferred_row_count = current_user.preferred_domain_csr_row_count
-
@per_page = params[:per_page] || preferred_row_count.or_else("10")
-
Domain.csr_per_page = @per_page if Domain.csr_per_page != @per_page
-
-
if @per_page != preferred_row_count
-
current_user.preferred_domain_csr_row_count = @per_page
-
current_user.save(validate: false)
-
end
-
-
@p = {page: (params[:page] || 1), per_page: @per_page}
-
end
-
end
-
class EnhancedResponder < ActionController::Responder
-
=begin
-
include CachedResponder
-
include FlashResponder
-
=end
-
include PaginatedResponder
-
end
-
class FoldersController < ApplicationController
-
before_filter :find_ssl_account
-
before_filter :set_ssl_slug
-
before_filter :find_folder, only: [
-
:update,
-
:destroy,
-
:add_certificate_order,
-
:add_certificate_orders
-
]
-
-
filter_access_to :all
-
filter_access_to [
-
:add_certificate_order,
-
:add_certificate_orders,
-
:destroy,
-
:update
-
], attribute_check: true
-
-
def index
-
@search = params[:search] || ""
-
if params[:search]
-
@certificate_orders = find_certificate_orders(source: 'folders')
-
@certificate_order_ids = @certificate_orders.pluck(:id)
-
@folders = if @certificate_order_ids.any?
-
Folder.joins(:certificate_orders).where(
-
certificate_orders: {id: @certificate_order_ids}
-
).uniq
-
else
-
[]
-
end
-
else
-
@folders = get_team_root_folders
-
end
-
@folder_ids = @folders.map(&:id)
-
end
-
-
def create
-
new_params = params[:folder].merge(ssl_account_id: @ssl_account.id)
-
new_params = new_params.merge(parent_id: nil) if parent_root?
-
@folder = Folder.new(new_params)
-
if @folder.save
-
render json: { folder_id: @folder.id }, status: :ok
-
else
-
render json: @folder.errors.messages, status: :unprocessable_entity
-
end
-
end
-
-
def children
-
if params[:search]
-
@certificate_order_ids = find_certificate_orders(source: 'folders').pluck(:id)
-
@folders = if params[:id] == '#'
-
get_team_root_folders.where(id: params[:folder_ids]).order(name: :asc)
-
else
-
@ssl_account.folders.where(
-
parent_id: params[:id], id: params[:folder_ids]
-
).order(name: :asc)
-
end
-
else
-
@folders = if params[:id] == '#'
-
get_team_root_folders.order(name: :asc)
-
else
-
@ssl_account.folders.includes{certificate_orders.certificate_contents.csrs}.
-
where(parent_id: params[:id]).order(name: :asc)
-
end
-
end
-
@tree_type = params[:tree_type]
-
render partial: 'folder_children'
-
end
-
-
def reset_to_system
-
Folder.reset_to_system_folders(@ssl_account)
-
redirect_to folders_path(@ssl_slug),
-
notice: "Certificates have been sorted into to system folders."
-
end
-
-
def update
-
if @folder
-
case params[:update_type]
-
when 'rename' then update_rename
-
when 'default' then update_default
-
when 'move' then update_move
-
end
-
else
-
render_try_again_error
-
end
-
end
-
-
def destroy
-
if @folder && @folder.can_destroy?
-
if @folder.destroy
-
render json: { message: "Folder successfully deleted." }, status: :ok
-
else
-
render_try_again_error
-
end
-
else
-
render json: { folder: ['System folders cannot be deleted.'] },
-
status: :unprocessable_entity
-
end
-
end
-
-
def add_certificate_order
-
if @folder
-
co = CertificateOrder.unscoped.find_by(ref: params[:folder][:certificate_order_id])
-
end
-
-
if @folder && co
-
if co.update_column(:folder_id, @folder.id)
-
render json: { message: "Certificate has been successfully moved." }, status: :ok
-
else
-
render_try_again_error
-
end
-
else
-
render_try_again_error
-
end
-
end
-
-
def add_certificate_orders
-
co_refs = params[:folder][:folder_certificate_order_ids].split(',')
-
if @folder && co_refs.any?
-
certificate_orders = CertificateOrder.unscoped.where(ref: co_refs)
-
end
-
if @folder && certificate_orders && certificate_orders.any?
-
certificate_orders.update_all(folder_id: @folder.id)
-
if certificate_orders.map(&:folder_id).uniq == [@folder.id]
-
flash[:notice] = "Certifiate Orders #{certificate_orders.map(&:ref).uniq.join(', ')} were successfully moved to folder #{@folder.name}"
-
else
-
flash[:error] = "Something went wrong, please try again."
-
end
-
else
-
flash[:error] = "Please select at least one certificate order to place in folder."
-
end
-
redirect_to certificate_orders_path(@ssl_slug, folders: true)
-
end
-
-
private
-
-
def render_try_again_error
-
render json: { folder: ['Something went wrong, please try again.'] },
-
status: :unprocessable_entity
-
end
-
-
def find_folder
-
@folder = Folder.find(params[:id])
-
end
-
-
def update_rename
-
if @folder && @folder.can_destroy?
-
if @folder.update(name: params[:folder][:name])
-
render json: { message: "Folder successfully renamed." }, status: :ok
-
else
-
render json: @folder.errors.messages, status: :unprocessable_entity
-
end
-
else
-
render json: { folder: ['System folders cannot be renamed.'] },
-
status: :unprocessable_entity
-
end
-
end
-
-
def update_default
-
if @folder && @folder.can_destroy?
-
if @folder.update(default: true)
-
@folder.ssl_account.update(default_folder_id: @folder.id)
-
render json: { message: "Folder successfully set as default." }, status: :ok
-
else
-
render json: @folder.errors.messages, status: :unprocessable_entity
-
end
-
else
-
render json: { default: ['System folders cannot be set as default folder'] },
-
status: :unprocessable_entity
-
end
-
end
-
-
def update_move
-
new_value = parent_root? ? nil : params[:folder][:parent_id]
-
if @folder.update(parent_id: new_value)
-
render json: { message: "Folder successfully moved." }, status: :ok
-
else
-
render json: @folder.errors.messages, status: :unprocessable_entity
-
end
-
end
-
-
def parent_root?
-
params[:parent_id] == '#' || params[:folder][:parent_id] == '#'
-
end
-
-
def get_team_root_folders
-
@ssl_account.folders.roots
-
end
-
-
def set_ssl_slug(target_user=nil)
-
if current_user && !params[:search].blank?
-
@ssl_account = current_user.ssl_account
-
end
-
if current_user && @ssl_account
-
@ssl_slug ||= (@ssl_account.ssl_slug || @ssl_account.acct_number)
-
end
-
end
-
end
-
class FundedAccountsController < ApplicationController
-
include OrdersHelper, CertificateOrdersHelper, FundedAccountsHelper
-
before_filter :go_prev, :parse_certificate_orders, only: [:apply_funds, :create_free_ssl]
-
# resource_controller :singleton
-
# ssl_required :allocate_funds, :allocate_funds_for_order, :apply_funds,
-
# :deposit_funds
-
# belongs_to :user
-
before_filter :require_user, :only => [:allocate_funds_for_order,
-
:deposit_funds, :allocate_funds, :apply_funds, :confirm_funds]
-
before_filter :find_ssl_account
-
skip_before_filter :finish_reseller_signup
-
filter_access_to :all
-
-
def allocate_funds
-
@funded_account = @ssl_account.funded_account
-
@funded_account.deduct_order = "false"
-
@reseller_initial_deposit = true if initial_reseller_deposit?
-
end
-
-
# apply funds from funded_account to purchase the order
-
def allocate_funds_for_order
-
@funded_account = current_user ? @ssl_account.funded_account : FundedAccount.new
-
@funded_account.deduct_order = "true"
-
if params[:id] == "certificate"
-
@certificate_order = @ssl_account.certificate_orders.current
-
@funded_account.order_type = "certificate"
-
elsif params[:id] == "order"
-
certificates_from_cookie
-
@funded_account.order_type = "order"
-
end
-
render :action => "allocate_funds"
-
end
-
-
# Deposit funds into the funded_account
-
def deposit_funds
-
too_many_declines = delay_transaction?
-
@reseller_initial_deposit = true if initial_reseller_deposit?
-
@funded_account, @billing_profile =
-
FundedAccount.new(params[:funded_account]),
-
BillingProfile.new(params[:billing_profile])
-
# After discount, check if sufficient funds in funded account for final amount
-
if @funded_account.deduct_order? && params[:discount_amount] && sufficient_funds?(params)
-
new_params = params.select{|k,v| %w{funded_account discount_code discount_amount}.include?(k)}
-
redirect_to apply_funds_path(new_params.deep_symbolize_keys) and return
-
end
-
if @funded_account.order_type=='certificate'
-
@certificate_order = @ssl_account.certificate_orders.current
-
elsif @funded_account.order_type=='order'
-
setup_orders
-
end
-
if params["prev.x".intern]
-
if @ssl_account.has_role?('new_reseller')
-
@ssl_account.reseller.back!
-
redirect_to new_account_reseller_url and return
-
elsif @certificate_order
-
return go_back_to_buy_certificate
-
elsif @certificate_orders
-
redirect_to show_cart_orders_url and return
-
end
-
end
-
account = @ssl_account
-
@funded_account.ssl_account = @billing_profile.ssl_account = account
-
@funded_account.funding_source = FundedAccount::NEW_CREDIT_CARD if @funded_account.funding_source.blank?
-
if @funded_account.valid?
-
@account_total = account.funded_account(true)
-
@funded_original = @account_total.cents
-
#if not deducting order, then it's a straight deposit since we don't deduct anything
-
@order ||= (@funded_account.deduct_order?)? current_order :
-
Order.new(:cents => 0, :deposit_mode => true)
-
if @funded_account.deduct_order?
-
deduct_order_amounts(params)
-
else
-
@account_total.cents += @funded_account.amount.cents - @order.cents
-
end
-
unless @funded_account.deduct_order?
-
# do this before we attempt to deduct funds
-
@funded_account.errors.add(:amount, "being loaded is not sufficient") if
-
@account_total.cents <= 0 #should redirect to load funds page prepopulated with the amount difference
-
if @funded_account.amount && (@funded_account.amount.to_s.to_f < Settings.minimum_deposit_amount)
-
@funded_account.errors.add(:amount,
-
"minimum deposit load amount is #{Money.new(Settings.minimum_deposit_amount.to_i*100).format}"
-
)
-
end
-
end
-
end
-
if(@funded_account.funding_source!=FundedAccount::NEW_CREDIT_CARD) #existing credit card
-
@profile = BillingProfile.find(@funded_account.funding_source)
-
else
-
@profile = @billing_profile
-
@billing_profile.valid?
-
end
-
render :action => "allocate_funds", :id => account and
-
return unless(@funded_account.errors.empty? and
-
(@funded_account.funding_source==FundedAccount::NEW_CREDIT_CARD)?
-
@billing_profile.errors.empty? : true)
-
dep = Deposit.new({
-
:amount => @funded_account.amount.cents,
-
:full_name => @profile.full_name,
-
:credit_card => @profile.credit_card,
-
:last_digits => @profile.last_digits,
-
:payment_method => 'credit card'})
-
@deposit = account.purchase dep
-
if @funded_account.deduct_order? && @funded_withdrawal > 0
-
fund = Deposit.new(
-
amount: @funded_withdrawal,
-
full_name: "Team #{@ssl_account.get_team_name} funded account",
-
credit_card: 'N/A',
-
last_digits: 'N/A',
-
payment_method: 'Funded Account'
-
)
-
@funded = account.purchase fund
-
end
-
@credit_card = @profile.build_credit_card
-
if ActiveMerchant::Billing::Base.mode == :test ? true : @credit_card.valid?
-
@deposit.amount = @funded_account.amount
-
@deposit.description = "Deposit"
-
@funded.description = 'Funded Account Withdrawal' if @funded
-
if initial_reseller_deposit?
-
#get this before transaction so user cannot change the cookie, thus
-
#resulting in mismatched item purchased
-
immutable_cart_item = ResellerTier.find_by_label(current_order.
-
line_items.first.sellable.label)
-
end
-
unless too_many_declines
-
options = @profile.build_info("Deposit").merge(owner_email: @ssl_account.get_account_owner.email)
-
@gateway_response = @deposit.purchase(@credit_card, options)
-
end
-
if @gateway_response && @gateway_response.success?
-
@deposit.mark_paid!
-
flash.now[:notice] = @gateway_response.message
-
save_billing_profile if
-
(@funded_account.funding_source == "new credit card")
-
@deposit.billing_profile = @profile
-
if apply_order
-
@order.deducted_from = @deposit
-
@ssl_account.orders << @order
-
apply_discounts(@order) #this needs to happen before the transaction but after the final incarnation of the order
-
@order.commit_discounts
-
record_order_visit(@order)
-
@order.mark_paid!
-
@order.credit_affiliate(cookies)
-
end
-
@account_total.save
-
dep.save
-
@deposit.save
-
if @funded
-
@funded.notes = "Partial payment for order ##{@order.reference_number} ($#{@order.amount.to_s})."
-
fund.save
-
@funded.save
-
@funded.mark_paid!
-
end
-
if initial_reseller_deposit?
-
account.reseller.finish_signup immutable_cart_item
-
end
-
log_deposit
-
OrderNotifier.deposit_completed(account, @deposit).deliver if Settings.invoice_notify
-
if @certificate_order
-
@certificate_order.pay! @gateway_response.success?
-
route ||= "edit"
-
elsif @certificate_orders
-
clear_cart
-
flash[:notice] = "Order successfully placed. %s"
-
flash[:notice_item] = "Click here to finish processing your
-
ssl.com certificates.", credits_certificate_orders_path
-
route ||= "order"
-
end
-
route ||= "success"
-
else
-
log_declined_transaction(@gateway_response, @credit_card.number.last(4)) if @gateway_response
-
@deposit.destroy
-
if @funded
-
@funded.destroy
-
@account_total.cents = @funded_original # put original amount back on the funded account
-
end
-
if @funded_account.valid? && !@funded_account.deduct_order?
-
@ssl_account.funded_account.update(cents: @funded_original)
-
end
-
flash[:error] = @gateway_response.message if @gateway_response
-
flash[:error] = 'Too many failed attempts, please wait 1 minute to try again!' if too_many_declines
-
end
-
route ||= "allocate"
-
end
-
route ||= "allocate"
-
respond_to do |format|
-
case route
-
when /allocate/
-
format.html { render :action => "allocate_funds" }
-
when /success/
-
format.html { render :action => "success" }
-
when /order/
-
format.html { redirect_to @order }
-
when /edit/
-
redirect_to edit_certificate_order_path(@certificate_order) and return
-
end
-
end
-
rescue Payment::AuthorizationError => error
-
flash.now[:error] = error.message
-
render :action => 'allocate_funds'
-
end
-
-
def apply_funds
-
@account_total = @funded_account = @ssl_account.funded_account
-
apply_discounts(@order) #this needs to happen before the transaction but after the final incarnation of the order
-
@funded_account.cents -= @order.final_amount.cents unless @funded_account.blank?
-
respond_to do |format|
-
if @funded_account.cents >= 0 and @order.line_items.size > 0
-
@funded_account.deduct_order = true
-
if @order.final_amount.cents > 0
-
record_order_visit(@order)
-
@order.mark_paid!
-
end
-
@funded_account.save
-
flash.now[:notice] = "The transaction was successful."
-
if @certificate_order
-
@certificate_order.pay! true
-
return redirect_to edit_certificate_order_path(@certificate_order)
-
elsif @certificate_orders
-
@ssl_account.orders << @order
-
clear_cart
-
flash[:notice] = "Order successfully placed. %s"
-
flash[:notice_item] = "Click here to finish processing your
-
ssl.com certificates.", credits_certificate_orders_path
-
format.html { redirect_to @order }
-
end
-
format.html { render :action => "success" }
-
else
-
if @order.line_items.size == 0
-
flash.now[:error] = "Cart is currently empty"
-
elsif @funded_account.cents <= 0
-
flash.now[:error] = "There is insufficient funds in your SSL account"
-
end
-
format.html { render :action => "confirm_funds" }
-
end
-
end
-
end
-
-
def create_free_ssl
-
respond_to do |format|
-
if @order.cents == 0 and @order.line_items.size > 0
-
record_order_visit(@order)
-
@order.give_away!
-
if @certificate_order
-
@certificate_order.pay! true
-
return redirect_to edit_certificate_order_path(@certificate_order)
-
elsif @certificate_orders
-
@ssl_account.orders << @order
-
clear_cart
-
flash[:notice] = "Order successfully placed. %s"
-
flash[:notice_item] = "Click here to finish processing your
-
ssl.com certificates.", credits_certificate_orders_path
-
format.html { redirect_to @order }
-
end
-
format.html { render :action => "success" }
-
else
-
if @order.line_items.size == 0
-
flash.now[:error] = "Cart is currently empty"
-
elsif @order.cents > 0
-
flash.now[:error] = "Cannot process non-free products"
-
end
-
if @certificate_order
-
return go_back_to_buy_certificate
-
else
-
format.html { redirect_to show_cart_orders_url }
-
end
-
end
-
end
-
end
-
-
def confirm_funds
-
if params[:id]=='order'
-
certificates_from_cookie
-
else
-
@certificate_order = @ssl_account.certificate_orders.current
-
check_for_current_certificate_order
-
end
-
end
-
-
private
-
-
def object
-
@object = @ssl_account.funded_account ||= FundedAccount.new(:amount => 0)
-
end
-
-
def save_certificate_orders
-
@ssl_account.orders << @order
-
OrderNotifier.certificate_order_prepaid(@ssl_account, @order).deliver
-
@order.line_items.each do |cert|
-
@ssl_account.cached_certificate_orders << cert.sellable
-
cert.sellable.pay! true
-
end
-
end
-
-
def deduct_order_amounts(params)
-
discount = params[:discount_amount]
-
discount = (discount && discount.to_f > 0) ? to_cents(discount) : 0
-
price_w_discount = @funded_account.amount.cents - discount
-
@funded_original = @account_total.cents # existing amount on funded account
-
@funded_withdrawal = @account_total.cents # credited toward purchase amount from funded account
-
# target amount user has chosen to deposit to go towards order amount
-
# and/or additional deposit to funded account if in surplus
-
@funded_target = Money.new(@funded_account.target_amount.to_f * 100)
-
-
# determine whether to tap into existing funds in the funded account
-
@funded_diff = @funded_target.cents - (price_w_discount - @funded_withdrawal)
-
if (@funded_diff >= 0) # deposit will cover cost of purchase and/or surplus for funded account
-
@account_total.cents += @funded_diff if (@funded_diff > 0)
-
end
-
@funded_account.amount = @funded_target
-
@account_total.cents -= @funded_withdrawal
-
end
-
-
def log_deposit
-
unless @funded_account.deduct_order?
-
gateway = BillingProfile.gateway_stripe? ? 'Stripe' : 'Authorize.net'
-
notes = [
-
"User #{current_user.login} has made a deposit",
-
"(order id: #{@gateway_response.order_id}) of $#{@funded_account.amount}",
-
"for team #{@ssl_account.get_team_name} through #{gateway} merchant."
-
]
-
SystemAudit.create(
-
owner: current_user,
-
target: @ssl_account.funded_account,
-
action: 'Made a deposit to funded account (FundedAccountsController#deposit_funds).',
-
notes: notes.join(' ')
-
)
-
end
-
end
-
-
def sufficient_funds?(params)
-
funded_amt = @ssl_account.funded_account.amount.cents
-
order_amt = to_cents(params[:funded_account][:amount])
-
discount = params[:discount_amount]
-
discount_amt = (discount && discount.to_f > 0) ? to_cents(discount) : 0
-
(funded_amt - (order_amt - discount_amt)) >= 0
-
end
-
-
def to_cents(amount)
-
Money.new(amount.to_f * 100).cents
-
end
-
end
-
class InvoicesController < ApplicationController
-
include OrdersHelper
-
-
before_filter :find_ssl_account, except: :index
-
before_filter :set_ssl_slug, except: :index
-
before_filter :find_invoice, except: :index
-
-
filter_access_to :all
-
filter_access_to :show, :update_invoice
-
-
def index
-
@invoices = invoices_base_query
-
@invoices = @invoices.index_filter(params) if params[:commit]
-
@invoices = @invoices.paginate(page: params[:page], per_page: 25)
-
end
-
-
def download
-
if @invoice
-
render pdf: "ssl.com_#{@ssl_account.get_invoice_label}_invoice_#{@invoice.reference_number}"
-
else
-
flash[:error] = "This invoice doesn't exist."
-
redirect_to :back
-
end
-
end
-
-
def show
-
@order = @invoice.payment unless @invoice.nil? || @invoice.payment.nil?
-
end
-
-
def manage_items
-
-
end
-
-
def transfer_items
-
orders = @invoice.orders.where(reference_number: params[:orders].split(','))
-
orders_count = orders.count
-
if orders_count > 0
-
invoice = if params[:invoice] == 'new_invoice'
-
Invoice.create_invoice_for_team(@invoice.billable.id)
-
else
-
Invoice.find_by(reference_number: params[:invoice])
-
end
-
orders.update_all(invoice_id: invoice.id)
-
@invoice.destroy unless @invoice.orders.any?
-
flash[:notice] = "All #{orders_count} order(s) have been successfully transferred to invoice ##{invoice.reference_number}."
-
redirect_to invoice_path(@ssl_slug, invoice.reference_number)
-
else
-
flash[:error] = "Please select at least one order!"
-
redirect_to manage_items_invoice_path(@ssl_slug, @invoice.reference_number)
-
end
-
end
-
-
def edit
-
end
-
-
def update
-
@invoice.update(params[:invoice]) if @invoice && params[:invoice]
-
respond_to do |format|
-
if @invoice.errors.any?
-
format.json { render json: @invoice.errors, status: :unprocessable_entity }
-
else
-
format.json { render json: @invoice, status: :ok }
-
end
-
end
-
end
-
-
def new_payment
-
@payable_invoice = true
-
end
-
-
def make_payment
-
@payable_invoice = true
-
ucc_or_invoice_params
-
-
@order = Order.new(
-
billing_profile_id: params[:funding_source],
-
amount: @target_amount,
-
cents: (@target_amount * 100).to_i,
-
description: @ssl_account.get_invoice_pmt_description,
-
state: 'pending',
-
approval: 'approved',
-
notes: order_invoice_notes
-
)
-
@order.billable = @ssl_account
-
@order.save
-
-
if @funded_amount > 0 && (@order_amount <= @funded_amount)
-
# All amount covered by credit from funded account
-
payment_funded_account
-
else
-
# Pay full or partial payment by CC or Paypal
-
payment_hybrid
-
end
-
end
-
-
def credit
-
amount = params[:invoice][:amount].to_f
-
-
if @invoice && !@invoice.refunded? && amount > 0
-
payment = @invoice.payment
-
max = @invoice.max_credit.to_s.to_f
-
amount = max if max <= amount
-
imvoice_amount = @invoice.get_amount.to_s.to_f
-
refunds = Money.new(@invoice.get_merchant_refunds).to_s.to_f
-
f_amount = Money.new(amount*100).format
-
-
if amount > 0
-
@invoice.billable.funded_account.add_cents(amount*100)
-
if (amount == imvoice_amount) || ((amount + refunds) == imvoice_amount)
-
@invoice.full_refund!
-
payment.full_refund! unless payment.fully_refunded?
-
else
-
@invoice.partial_refund!
-
end
-
-
SystemAudit.create(
-
owner: current_user,
-
target: @invoice,
-
notes: "Credit issued with reason: #{params[:invoice][:credit_reason]}",
-
action: "#{@ssl_account.get_invoice_label.capitalize} Invoice ##{@invoice.reference_number}, credit issued for #{f_amount}."
-
)
-
end
-
flash[:notice] = "Invoice was successfully credited for amount #{f_amount}."
-
else
-
flash[:error] = "This invoice cannot be credited."
-
end
-
redirect_to_invoice
-
end
-
-
def refund_other
-
if @invoice && !@invoice.refunded?
-
payment = @invoice.payment
-
payment_type = Invoice::PAYMENT_METHODS_TEXT[params[:refund_type].to_sym]
-
@invoice.full_refund!
-
payment.full_refund! unless payment.fully_refunded?
-
SystemAudit.create(
-
owner: current_user,
-
target: @invoice,
-
notes: "Full refund issued for payment type #{payment_type}.",
-
action: "#{@ssl_account.get_invoice_label.capitalize} Invoice ##{@invoice.reference_number}, refund issued for #{payment.amount.format}."
-
)
-
flash[:notice] = "Invoice was successfully refunded for payment type #{payment_type}."
-
else
-
flash[:error] = "This invoice is already refunded."
-
end
-
redirect_to_invoice
-
end
-
-
def remove_item
-
if @invoice && !@invoice.paid?
-
o = @invoice.orders.find_by(reference_number: params[:item_ref])
-
o.update(approval: 'rejected')
-
flash[:notice] = "Item #{o.reference_number} has been removed from invoice."
-
else
-
flash[:error] = "Something went wrong or invoice has already been paid."
-
end
-
redirect_to_invoice
-
end
-
-
def add_item
-
if @invoice && !@invoice.paid?
-
o = @invoice.orders.find_by(reference_number: params[:item_ref])
-
o.update(approval: 'approved')
-
flash[:notice] = "Item #{o.reference_number} has been added back to invoice."
-
else
-
flash[:error] = "Something went wrong or invoice has already been paid."
-
end
-
redirect_to_invoice
-
end
-
-
def update_item
-
if @invoice
-
o = @invoice.orders.find_by(reference_number: params[:item_ref])
-
if o
-
o.update(invoice_description: params[:item_description]) unless params[:item_description].blank?
-
flash[:notice] = "Item #{o.reference_number} description has been updated."
-
end
-
else
-
flash[:error] = "Something went wrong, please try again."
-
end
-
redirect_to_invoice
-
end
-
-
def make_payment_other
-
pmt_type = Invoice::PAYMENT_METHODS_TEXT[params[:ptm_type].to_sym]
-
if @invoice && !@invoice.paid?
-
@order = Order.new(
-
amount: @invoice.get_amount,
-
cents: @invoice.get_cents,
-
description: @ssl_account.get_invoice_pmt_description,
-
state: 'paid',
-
approval: 'approved',
-
notes: order_invoice_notes << " Paid full amount of #{@invoice.get_amount_format} by #{pmt_type}."
-
)
-
@order.billable = @ssl_account
-
@order.save
-
-
if @order.persisted? && @invoice.update(status: 'paid', order_id: @order.id)
-
flash[:notice] = "Paid full amount of #{@invoice.get_amount_format} by #{pmt_type}."
-
else
-
@order.destroy
-
flash[:error] = "Something went wrong, please try again."
-
end
-
else
-
flash[:error] = "Invoice was already paid off."
-
end
-
redirect_to_invoice
-
end
-
-
def destroy
-
if @invoice
-
if @invoice.archive!
-
flash[:notice] = "Invoice #{@invoice.reference_number} successfully deleted."
-
else
-
flash[:error] = "Something went wrong, please try again!"
-
redirect_to_invoice
-
end
-
end
-
redirect_to_invoice
-
end
-
-
private
-
-
def invoices_base_query
-
base = if current_user.is_system_admins?
-
(@ssl_account.try(:invoices) ? Invoice.unscoped{@ssl_account.try(:invoices).where.not(status: 'archived')} :
-
Invoice.where.not(billable_id: nil, type: nil))
-
else
-
current_user.ssl_account.invoices.where.not(status: 'archived')
-
end
-
base.includes(:orders).uniq.sort_with(params)
-
end
-
-
def payment_hybrid
-
if current_user && order_reqs_valid? && !@too_many_declines && purchase_successful?
-
save_billing_profile unless (params[:funding_source])
-
@order.billing_profile = @profile
-
@order.save
-
withdraw_funded_account((@funded_amount * 100).to_i) if @funded_amount > 0
-
invoice_paid
-
record_order_visit(@order)
-
-
flash[:notice] = "Succesfully paid for invoice #{@invoice.reference_number}."
-
redirect_to_invoice
-
else
-
flash[:error] = if @too_many_declines
-
'Too many failed attempts, please wait 1 minute to try again!'
-
else
-
@gateway_response.message
-
end
-
redirect_new_payment
-
end
-
rescue Payment::AuthorizationError => error
-
flash[:error] = error.message
-
redirect_new_payment
-
end
-
-
def payment_funded_account
-
withdraw_amount = @order_amount < @funded_amount ? @order_amount : @funded_amount
-
withdraw_amount = (withdraw_amount * 100).to_i
-
withdraw_amount_str = Money.new(withdraw_amount).format
-
-
withdraw_funded_account(withdraw_amount)
-
-
if current_user && @order.valid? &&
-
((@ssl_account.funded_account.cents + withdraw_amount) == @funded_account_init)
-
save_free_order
-
invoice_paid
-
flash[:notice] = "Succesfully paid full amount of #{withdraw_amount_str} from funded account for invoice."
-
redirect_to_invoice
-
else
-
flash[:error] = "Something went wrong, did not withdraw #{withdraw_amount_str} from funded account!"
-
redirect_new_payment
-
end
-
end
-
-
def save_free_order
-
@order.billing_profile_id = nil
-
@order.deducted_from_id = nil
-
@order.state = 'paid'
-
record_order_visit(@order)
-
@order.save
-
end
-
-
def invoice_paid
-
if @order.persisted?
-
@invoice.update(order_id: @order.id, status: 'paid')
-
@invoice.notify_invoice_paid(current_user) if Settings.invoice_notify
-
end
-
end
-
-
def redirect_new_payment
-
new_params = {ssl_slug: @ssl_slug,id: @invoice.reference_number}
-
if params[:billing_profile]
-
new_params[:billing_profile] = params[:billing_profile].delete_if do |k, v|
-
%w{card_number security_code stripe_card_token}.include?(k)
-
end
-
end
-
redirect_to new_payment_invoice_path(new_params)
-
end
-
-
def redirect_to_invoice
-
redirect_to invoice_path(@ssl_slug, @invoice.reference_number)
-
end
-
-
def find_ssl_account
-
if current_user
-
ref = params[:order].nil? ? params[:id] : params[:order][:id]
-
@ssl_account = if current_user.is_system_admins?
-
Invoice.find_by(reference_number: ref).billable
-
else
-
current_user.ssl_account
-
end
-
end
-
end
-
-
def find_invoice
-
if current_user
-
ref = params[:order].nil? ? params[:id] : params[:order][:id]
-
@invoice = if current_user.is_system_admins?
-
Invoice.find_by(reference_number: ref)
-
else
-
current_user.ssl_account.invoices.find_by(reference_number: ref)
-
end
-
switch_to_invoice_team
-
end
-
end
-
-
def switch_to_invoice_team
-
unless current_user.is_system_admins?
-
ref = params[:order].nil? ? params[:id] : params[:order][:id]
-
approved_teams = current_user.get_all_approved_accounts
-
# Couldn't find invoice in users default team.
-
if @invoice.nil?
-
@invoice = approved_teams.map(&:invoices).flatten.find { |i| i.reference_number == ref }
-
end
-
# Switch user to invoices team
-
if @invoice && @invoice.billable != @ssl_account &&
-
approved_teams.map(&:id).include?(@invoice.billable.id)
-
-
current_user.set_default_ssl_account(@invoice.billable.id)
-
flash[:notice] = "You have switched to team %s."
-
flash[:notice_item] = "<strong>#{current_user.ssl_account.get_team_name}</strong>"
-
set_ssl_slug(current_user)
-
end
-
end
-
end
-
end
-
class MailboxController < ApplicationController
-
before_action :find_ssl_account
-
before_action :get_mailbox
-
before_action :unread_messages_count
-
-
filter_access_to :all
-
-
def inbox
-
@emails = @mailbox.inbox
-
@email_type = :inbox
-
end
-
-
def sent
-
@emails = @mailbox.sentbox
-
@email_type = :sent
-
end
-
-
def trash
-
@emails = @mailbox.trash
-
@email_type = :trash
-
end
-
-
def compose
-
@email_type = :compose
-
if request.post?
-
recipients = User.where(email: params[:mail_recipients])
-
@conversation = current_user.send_message(recipients, params[:mail_body], params[:mail_subject]).conversation
-
-
redirect_to mail_read_path(@ssl_slug, conversation_id: @conversation),
-
success: "Your message was successfully sent!"
-
end
-
end
-
-
def reply
-
get_conversation
-
if @conversation
-
current_user.reply_to_conversation(@conversation, params[:body])
-
end
-
redirect_to mail_read_path(@ssl_slug, conversation_id: @conversation),
-
notice: "Your reply message was successfully sent!"
-
end
-
-
def read
-
get_conversation
-
if @conversation
-
@receipts = @conversation.receipts_for(current_user)
-
@conversation.mark_as_read(current_user)
-
else
-
redirect_to mail_inbox_path(@ssl_slug),
-
error: "Could not locate this email, please try again!"
-
end
-
@email_type = :read
-
end
-
-
def move_to_trash
-
get_conversation
-
if @conversation
-
@conversation.move_to_trash(current_user)
-
flash[:notice] = "Successfully moved email to trash."
-
else
-
flash[:error] = "Something went wrong, please try again."
-
end
-
redirect_to mail_inbox_path(@ssl_slug)
-
end
-
-
private
-
-
def get_conversation
-
if @mailbox && params[:conversation_id]
-
@conversation = @mailbox.conversations.find(params[:conversation_id])
-
end
-
end
-
-
def get_mailbox
-
if current_user
-
@mailbox ||= current_user.mailbox
-
end
-
end
-
-
def unread_messages_count
-
if @mailbox
-
@unread_messages = @mailbox.inbox(unread: true).uniq.count
-
end
-
end
-
end
-
class ManagedCsrsController < ApplicationController
-
before_filter :require_user, :set_ssl_slug, except: [:new, :add_generated_csr]
-
before_filter :set_row_page, only: [:index]
-
before_filter :set_sign_hash_algorithms, :find_ssl_account, only: [:new]
-
-
def index
-
@csrs = (current_user.ssl_account.all_csrs).paginate(@p)
-
end
-
-
def new
-
if params[:cert_ref]
-
@cert_ref = params[:cert_ref]
-
@for_reprocess = params[:is_reprocess]
-
@certificate_order=@ssl_account.certificate_orders.find_by_ref(@cert_ref)
-
elsif params[:cert_token]
-
@is_server = params[:is_server]
-
@cert_token = params[:cert_token]
-
co_token = CertificateOrderToken.find_by_token(params[:cert_token])
-
@error_cert_ref = co_token.certificate_order.ref
-
end
-
-
unless current_user.blank?
-
@csr = ManagedCsr.new
-
@cert_orders = current_user.ssl_account.certificate_orders.unused.map{|cert_order| [cert_order.ref, cert_order.id]}
-
end
-
end
-
-
def create
-
# redirect_to new_managed_csr_path(@ssl_slug) and return unless current_user
-
# @csr = ManagedCsr.new(params[:managed_csr])
-
# @csr.ssl_account_id = current_user.ssl_account.id
-
# respond_to do |format|
-
# if !current_user.ssl_account.all_csrs.find_by_public_key_sha1(@csr.public_key_sha1).blank?
-
# flash[:notice] = "Csr already exists on team #{current_user.ssl_account.ssl_slug}."
-
# format.html {redirect_to managed_csrs_path(@ssl_slug)}
-
# elsif @csr.save
-
# flash[:notice] = "Csr was successfully added."
-
# format.html {redirect_to managed_csrs_path(@ssl_slug)}
-
# else
-
# flash[:error] = "There was a problem adding this CSR to the CSR Manager"
-
# format.html {redirect_to new_managed_csr_path(@ssl_slug)}
-
# end
-
# end
-
-
redirect_to new_managed_csr_path(@ssl_slug) and return unless current_user
-
@csr = ManagedCsr.new
-
@csr.friendly_name = params[:friendly_name] && !params[:friendly_name].empty? ? params[:friendly_name] : nil
-
@csr.body = params[:csr]
-
@csr.ssl_account_id = current_user.ssl_account.id
-
-
respond_to do |format|
-
if !current_user.ssl_account.all_csrs.find_by_public_key_sha1(@csr.public_key_sha1).blank?
-
flash[:notice] = "Csr already exists on team #{current_user.ssl_account.ssl_slug}."
-
format.html {redirect_to managed_csrs_path(@ssl_slug)}
-
elsif @csr.save
-
# certificate_order = @ssl_account.certificate_orders.find(params[:cert_order])
-
# certificate_order.certificate_content.csr = @csr
-
-
flash[:notice] = "Csr was successfully added."
-
format.html {redirect_to managed_csrs_path(@ssl_slug)}
-
else
-
flash[:error] = "There was a problem adding this CSR to the CSR Manager"
-
format.html {redirect_to new_managed_csr_path(@ssl_slug)}
-
end
-
end
-
end
-
-
def add_generated_csr
-
returnObj = {}
-
-
if params[:is_logged_in] == 'true'
-
if current_user
-
if params[:csr_id]
-
@csr = current_user.ssl_account.all_csrs.find_by(id: params[:csr_id])
-
@csr.body = params[:csr]
-
@csr.friendly_name = params[:friendly_name] && !params[:friendly_name].empty? ? params[:friendly_name] : nil
-
-
if @csr.save
-
returnObj['status'] = 'true'
-
returnObj['csr_ref'] = @csr.ref
-
returnObj['hash'] = @csr.public_key_sha1
-
else
-
returnObj['status'] = 'There was a problem adding this CSR to the CSR Manager.'
-
end
-
else
-
@csr = ManagedCsr.new
-
@csr.friendly_name = params[:friendly_name] && !params[:friendly_name].empty? ? params[:friendly_name] : nil
-
@csr.body = params[:csr]
-
@csr.ssl_account_id = current_user.ssl_account.id
-
-
if !current_user.ssl_account.all_csrs.find_by_public_key_sha1(@csr.public_key_sha1).blank?
-
returnObj['status'] = 'CSR already exists on team' + current_user.ssl_account.ssl_slug + '.'
-
elsif @csr.save
-
returnObj['status'] = 'true'
-
returnObj['csr_ref'] = @csr.ref
-
returnObj['hash'] = @csr.public_key_sha1
-
else
-
returnObj['status'] = 'There was a problem adding this CSR to the CSR Manager.'
-
end
-
end
-
else
-
returnObj['status'] = 'no_user'
-
returnObj['url'] = new_user_session_url
-
end
-
else
-
@csr = ManagedCsr.new
-
@csr.body = params[:csr]
-
-
returnObj['status'] = 'true'
-
returnObj['hash'] = @csr.public_key_sha1
-
end
-
-
render :json => returnObj
-
end
-
-
def edit
-
@csr = current_user.ssl_account.all_csrs.find_by(id: params[:id])
-
end
-
-
def update
-
@csr = current_user.ssl_account.all_csrs.find_by(id: params[:id])
-
# @csr.friendly_name = params[:csr][:friendly_name]
-
# @csr.body = params[:csr][:body]
-
@csr.body = params[:csr]
-
@csr.friendly_name = params[:friendly_name] && !params[:friendly_name].empty? ? params[:friendly_name] : nil
-
@csr.save
-
-
redirect_to managed_csrs_path(@ssl_slug)
-
end
-
-
def destroy
-
@csr = current_user.ssl_account.all_csrs.find_by(id: params[:id])
-
if @csr
-
@csr.destroy
-
flash[:notice] = "Csr was successfully deleted."
-
else
-
flash[:error] = "Csr not found."
-
end
-
respond_to do |format|
-
format.html { redirect_to managed_csrs_path(@ssl_slug) }
-
end
-
end
-
-
def remove_managed_csrs
-
csr_ids = params['checkbox_csrs']
-
csr_ids.each do |csr_id|
-
csr = current_user.ssl_account.all_csrs.find_by(id: csr_id)
-
csr.destroy unless csr.blank?
-
end
-
-
render :json => 'success'
-
end
-
-
def show_csr_detail
-
if current_user
-
@csr = current_user.ssl_account.all_csrs.find_by(id: params[:id])
-
-
render :partial=>'detailed_info', :locals=>{:csr=>@csr}
-
else
-
render :json => 'no-user'
-
end
-
end
-
-
private
-
def set_row_page
-
@per_page = params[:per_page] ? params[:per_page] : 10
-
Csr.per_page = @per_page if Csr.per_page != @per_page
-
-
@p = {page: (params[:page] || 1), per_page: @per_page}
-
end
-
-
def set_sign_hash_algorithms
-
@sign_alg = [
-
['RSASSA-PKCS1-v1_5', 'RSASSA-PKCS1-v1_5'],
-
['ECDSA', 'ECDSA'],
-
['RSA-PSS', 'RSA-PSS']
-
]
-
-
@rsa_key_size = [
-
['2048', '2048'],
-
['4096', '4096']
-
]
-
-
@ec_key_size = [
-
['256', '256'],
-
['384', '384']
-
]
-
end
-
end
-
class ManagedUsersController < ApplicationController
-
before_filter :require_user
-
filter_access_to :new, :create
-
filter_access_to :edit, :update_roles, :remove_from_account, attribute_check: true
-
-
def new
-
@user=User.new
-
end
-
-
def create
-
ssl_account_ids = params[:user][:ssl_account_ids].reject(&:blank?).map(&:to_i).compact
-
user_exists = User.get_user_by_email(params[:user][:email])
-
if user_exists && user_exists.is_admin_disabled?
-
disabled_user_invited(user_exists, ssl_account_ids)
-
redirect_to users_path(ssl_slug: @ssl_slug)
-
else
-
manage_invites = current_user.total_teams_can_manage_users.map(&:id) & ssl_account_ids
-
@ssl_accounts = manage_invites.any? ? SslAccount.where(id: manage_invites) : []
-
ignore_teams = user_exists_for_teams(params[:user][:email])
-
ignore_teams = ignore_teams.map(&:get_team_name).join(', ') unless ignore_teams.empty?
-
if @ssl_accounts.empty?
-
@user = User.new
-
flash[:error] = if manage_invites.blank? && ssl_account_ids.any?
-
"You do not have permission to invite users to #{ssl_account_ids.count} team(s)!"
-
else
-
"User #{params[:user][:email]} already exists for these teams: #{ignore_teams}!"
-
end
-
render :new
-
else
-
new_params = params.merge(root_url: root_url, from_user: current_user)
-
@user = current_user.invite_user_to_account!(new_params)
-
if @user.persisted?
-
invite_user_to_team(
-
@user, new_params, (request.subdomain == Reseller::SUBDOMAIN), user_exists
-
)
-
flash_notice = "An invitation email has been sent to #{@user.email}
-
for teams #{@ssl_accounts.map(&:get_team_name).join(', ')}."
-
unless ignore_teams.blank? || ignore_teams.empty?
-
flash_notice << " User already exisits for team(s) #{ignore_teams}."
-
end
-
flash[:notice] = flash_notice
-
redirect_to users_path(ssl_slug: @ssl_slug)
-
else
-
render :new
-
end
-
end
-
end
-
end
-
-
def edit
-
@user = User.find(params[:id])
-
if current_user.is_system_admins?
-
@user_accounts_roles = User.get_user_accounts_roles(@user)
-
end
-
@role_ids = @user.roles_for_account(current_user.ssl_account)
-
render :update_roles
-
end
-
-
def update_roles
-
ssl_accounts = params[:user][:ssl_account_ids].reject(&:blank?).compact
-
role_ids = params[:user][:role_ids].reject(&:blank?)
-
role_change = params[:user][:role_change_type]
-
if ssl_accounts.empty? || role_ids.empty?
-
flash[:error] = 'Must select at least one role and one team.'
-
redirect_to edit_managed_user_path
-
else
-
params[:user][:role_ids] = (role_ids & User.roles_list_for_user(current_user).ids.map(&:to_s))
-
@user = User.find(params[:id])
-
ssl_select = ssl_accounts.map(&:to_i)
-
ssl_user = @user.ssl_accounts.pluck(:id)
-
ssl_update = SslAccount.where(id: (ssl_select & ssl_user)) # update roles for teams
-
@ssl_accounts = SslAccount.where(id: (ssl_select - ssl_user)) # invite to teams
-
-
# update roles for user's existing teams
-
ssl_update.map(&:id).each do |ssl|
-
params[:user][:ssl_account_id] = ssl
-
if role_change == 'overwrite'
-
@user.assign_roles(params)
-
@user.remove_roles(params)
-
elsif role_change == 'add'
-
@user.assign_roles(params)
-
else
-
@user.remove_roles(params, true)
-
end
-
end
-
# invite existing user to new teams w/selected roles
-
unless @ssl_accounts.empty?
-
new_params = params.merge(root_url: root_url, from_user: current_user)
-
invite_user_to_team(@user, new_params, (request.subdomain == Reseller::SUBDOMAIN), true)
-
end
-
notice = "#{@user.email} roles have been updated for teams: #{ssl_update.map(&:get_team_name).join(', ')}."
-
notice << " And, invited to teams: #{@ssl_accounts.map(&:get_team_name).join(', ')}." unless @ssl_accounts.empty?
-
@user.touch
-
redirect_to users_path(ssl_slug: @ssl_slug), notice: notice
-
end
-
end
-
-
def remove_from_account
-
@user = User.find(params[:id])
-
account = SslAccount.find(params[:ssl_account_id]) if params[:ssl_account_id]
-
account = account ? account : current_user.ssl_account
-
unless account.get_account_owner == @user
-
@user.remove_user_from_account(account, current_user)
-
flash[:notice] = "#{@user.email} has been removed from account '#{account.acct_number}' and is being notified."
-
else
-
flash[:notice] = "#{@user.email} is the owner of account '#{account.acct_number}' and cannot be removed."
-
end
-
redirect_to users_path(ssl_slug: @ssl_slug)
-
end
-
-
private
-
-
def get_role_ids(role_ids, reseller)
-
role_ids = role_ids || []
-
acc_admin_user = Role.get_account_admin_id
-
unless reseller || role_ids.include?(acc_admin_user.to_s)
-
role_ids << acc_admin_user if role_ids.empty?
-
end
-
role_ids << Role.get_role_id(Role::RESELLER) if reseller
-
role_ids
-
end
-
-
def user_exists_for_teams(email)
-
ignore_teams = []
-
@ssl_accounts = @ssl_accounts.inject([]) do |filtered_ssl, ssl|
-
user_exists = current_user.user_exists_for_account?(email, ssl)
-
ignore_teams << ssl if user_exists
-
filtered_ssl << ssl unless user_exists
-
filtered_ssl
-
end
-
ignore_teams
-
end
-
-
def invite_user_to_team(user, params, reseller, existing_user)
-
roles = (get_role_ids(params[:user][:role_ids], reseller)).reject(&:blank?).compact
-
@ssl_accounts.each do |ssl_account|
-
if reseller
-
ssl_account.add_role! 'new_reseller'
-
ssl_account.set_reseller_default_prefs
-
end
-
user.ssl_accounts << ssl_account
-
user.set_roles_for_account(ssl_account, roles)
-
if existing_user
-
params[:user][:ssl_account_id] = ssl_account.id
-
user.invite_existing_user(params)
-
end
-
SystemAudit.create(
-
owner: current_user,
-
target: user,
-
action: 'Invite user to team (ManagedUsersController#create)',
-
notes: "#{existing_user ? 'Ssl.com' : 'New'} user #{user.login} was invited to team #{ssl_account.get_team_name} by #{current_user.login}.")
-
end
-
unless existing_user
-
user.approve_all_accounts(:log_invite)
-
user.invite_new_user(params.merge(deliver_invite: true, invited_teams: @ssl_accounts))
-
end
-
end
-
-
def disabled_user_invited(disabled_user, ssl_account_ids)
-
ssl_accounts = SslAccount.where(id: ssl_account_ids.reject(&:blank?).compact)
-
if ssl_accounts.any?
-
ssl_accounts.each do |team|
-
disabled_user.deliver_invite_to_account_disabled!(team, current_user)
-
end
-
end
-
flash[:error] = "User #{params[:user][:email]} has been disabled by SSL.com and cannot be invited at this moment!"
-
end
-
end
-
class NotificationGroupsController < ApplicationController
-
before_action :require_user, only: [:index, :new, :create, :edit, :update, :destroy]
-
before_action :find_ssl_account
-
before_action :set_row_page, only: [:index, :search]
-
before_action :set_schedule_value, only: [:index, :new, :edit, :search]
-
-
def search
-
@filter_slt_type = params[:filter_type]
-
-
if params[:filter_type] == 'true'
-
@notification_groups = @ssl_account.notification_groups.paginate(@p)
-
else
-
@filter_slt_schedule_type = params[:filter_schedule_type]
-
-
if params[:filter_schedule_type] == 'true'
-
@filter_slt_schedule_simple = params[:filter_schedule_simple]
-
notification_group_ids = Schedule.where(schedule_type: 'Simple',
-
schedule_value: params[:filter_schedule_simple])
-
.pluck(:notification_group_id).uniq
-
@notification_groups = @ssl_account.notification_groups.where(id: notification_group_ids).paginate(@p)
-
else
-
notification_group_ids = []
-
-
if params[:filter_weekday_type] == 'true'
-
notification_group_ids.concat Schedule.
-
where(schedule_type: 'Weekday',
-
schedule_value: 'All').
-
pluck(:notification_group_id).uniq
-
else
-
@filter_slt_weekdays = params[:filter_weekday]
-
notification_group_ids.concat Schedule.
-
where(schedule_type: 'Weekday',
-
schedule_value: params[:filter_weekday]).
-
pluck(:notification_group_id).uniq
-
end
-
-
if params[:filter_month_type] == 'true'
-
notification_group_ids.concat Schedule.
-
where(schedule_type: 'Month',
-
schedule_value: 'All').
-
pluck(:notification_group_id).uniq
-
else
-
@filter_slt_months = params[:filter_month]
-
notification_group_ids.concat Schedule.
-
where(schedule_type: 'Month',
-
schedule_value: params[:filter_month]).
-
pluck(:notification_group_id).uniq
-
end
-
-
if params[:filter_day_type] == 'true'
-
notification_group_ids.concat Schedule.
-
where(schedule_type: 'Day',
-
schedule_value: 'All').
-
pluck(:notification_group_id).uniq
-
else
-
@filter_slt_days = params[:filter_day]
-
notification_group_ids.concat Schedule.
-
where(schedule_type: 'Day',
-
schedule_value: params[:filter_day]).
-
pluck(:notification_group_id).uniq
-
end
-
-
if params[:filter_hour_type] == 'true'
-
notification_group_ids.concat Schedule.
-
where(schedule_type: 'Hour',
-
schedule_value: 'All').
-
pluck(:notification_group_id).uniq
-
else
-
@filter_slt_hours = params[:filter_hour]
-
notification_group_ids.concat Schedule.
-
where(schedule_type: 'Hour',
-
schedule_value: params[:filter_hour]).
-
pluck(:notification_group_id).uniq
-
end
-
-
if params[:filter_minute_type] == 'true'
-
notification_group_ids.concat Schedule.
-
where(schedule_type: 'Minute',
-
schedule_value: 'All').
-
pluck(:notification_group_id).uniq
-
else
-
@filter_slt_minutes = params[:filter_minute]
-
notification_group_ids.concat Schedule.
-
where(schedule_type: 'Minute',
-
schedule_value: params[:filter_minute]).
-
pluck(:notification_group_id).uniq
-
end
-
-
@notification_groups = @ssl_account.notification_groups.where(id: notification_group_ids.uniq).paginate(@p)
-
end
-
end
-
-
respond_to do |format|
-
format.html { render :action => :index }
-
format.xml { render :xml => @notification_groups }
-
end
-
end
-
-
def index
-
@notification_groups = @ssl_account.notification_groups.paginate(@p)
-
end
-
-
def remove_groups
-
group_ids = params[:note_group_check]
-
-
unless group_ids.blank?
-
@ssl_account.notification_groups.where(id: group_ids).destroy_all
-
Preference.where(owner_type: 'NotificationGroup', owner_id: group_ids).destroy_all
-
Schedule.where(notification_group_id: group_ids).destroy_all
-
end
-
-
flash[:notice] = "Selected notification groups has been removed successfully."
-
redirect_to notification_groups_path(ssl_slug: @ssl_slug)
-
end
-
-
def scan_groups
-
# group_ids = params[:scan_groups]
-
group_ids = params[:note_group_check]
-
-
# if group_ids.blank?
-
# groups = @ssl_account.notification_groups
-
# else
-
# groups = @ssl_account.notification_groups.where(id: group_ids, status: true)
-
# end
-
-
groups = @ssl_account.notification_groups.where(id: group_ids, status: false)
-
-
# groups.includes(
-
# [:stored_preferences, {:certificate_orders =>
-
# [:orders, :certificate_contents =>
-
# {:csr => :signed_certificates}]}]).find_in_batches(batch_size: 250) do |batch_list|
-
if groups.size > 0
-
groups.find_in_batches(batch_size: 250) do |batch_list|
-
batch_list.each do |group|
-
# NotificationGroup.scan_notification_group(group)
-
group.scan_notification_group
-
end
-
end
-
-
flash[:notice] = "Scan has been done successfully for only enabled Notification Groups."
-
else
-
flash[:error] = "It can not scan for disabled Notification Group(s)."
-
end
-
-
redirect_to notification_groups_path(ssl_slug: @ssl_slug)
-
end
-
-
def change_status_groups
-
group_ids = params[:note_group_check]
-
note_group_status = params[:note_groups_status]
-
-
@ssl_account.notification_groups.where(id: group_ids).update_all(status: note_group_status == 'true')
-
-
flash[:notice] = "It has been updated status to " + note_group_status == 'true' ? 'Enable' : 'Disable' + " successfully."
-
redirect_to notification_groups_path(ssl_slug: @ssl_slug)
-
end
-
-
def scan_individual_group
-
notification_group = @ssl_account.notification_groups.includes(:notification_groups_subjects).find(params[:notification_group_id])
-
notification_group.scan_notification_group
-
-
flash[:notice] = "Scan has been done successfully."
-
redirect_to edit_notification_group_path(@ssl_slug, notification_group.id)
-
end
-
-
def new
-
certificate_names = @ssl_account.certificate_names.pluck(:name, :id)
-
@subjects_list = remove_duplicate(certificate_names)
-
.map{ |arr| [arr[0], arr[0] + '---' + arr[1].to_s] }
-
@contacts_list = remove_duplicate(@ssl_account.cached_certificate_orders.flatten.compact
-
.map(&:certificate_contents).flatten.compact
-
.map(&:certificate_contacts).flatten.compact.map{ |cct| [cct.email, cct.id] })
-
.map{ |arr| [arr[0], arr[0] + '---' + arr[1].to_s] }
-
@cos_list = @ssl_account.cached_certificate_orders.pluck(:ref, :id).uniq
-
@title = 'New SSL Expiration Notification Group'
-
-
render 'group'
-
end
-
-
def edit
-
@notification_group = @ssl_account.notification_groups.where(id: params[:id]).first
-
slt_cert_orders = @notification_group.certificate_orders.flatten.compact
-
@cos_list = @ssl_account.cached_certificate_orders.pluck(:ref, :id).uniq
-
@slt_cos_list = slt_cert_orders.map(&:id)
-
-
@slt_subjects_list = generate_slt_subjects
-
domain_names = @notification_group.notification_groups_subjects.where(subjectable_id: nil)
-
@subjects_list = remove_duplicate(@ssl_account.certificate_names.pluck(:name, :id))
-
.map{ |arr| [arr[0], @slt_subjects_list.include?(arr[1].to_s) ? arr[1] : (arr[0] + '---' + arr[1].to_s)] }
-
.concat(domain_names.pluck(:domain_name, :domain_name))
-
-
@slt_contacts_list = generate_slt_contacts
-
email_addresses = @notification_group.notification_groups_contacts.where(contactable_id: nil)
-
@contacts_list = remove_duplicate(
-
@ssl_account.cached_certificate_orders.flatten.compact
-
.map(&:certificate_contents).flatten.compact
-
.map(&:certificate_contacts).flatten.compact
-
.map{ |cct| [cct.email, cct.id] }
-
).map{ |arr| [arr[0], @slt_contacts_list.include?(arr[1].to_s) ? arr[1] : (arr[0] + '---' + arr[1].to_s)] }
-
.concat(email_addresses.pluck(:email_address, :email_address))
-
-
@slt_schedule_simple = @notification_group.schedules.where(schedule_type: 'Simple').
-
pluck(:schedule_value)
-
@slt_schedule_weekdays = @notification_group.schedules.where(schedule_type: 'Weekday').
-
pluck(:schedule_value)
-
@slt_schedule_months = @notification_group.schedules.where(schedule_type: 'Month').
-
pluck(:schedule_value)
-
@slt_schedule_days = @notification_group.schedules.where(schedule_type: 'Day').
-
pluck(:schedule_value)
-
@slt_schedule_hours = @notification_group.schedules.where(schedule_type: 'Hour').
-
pluck(:schedule_value)
-
@slt_schedule_minutes = @notification_group.schedules.where(schedule_type: 'Minute').
-
pluck(:schedule_value)
-
-
@title = 'Edit SSL Expiration Notification Group'
-
-
render 'group'
-
end
-
-
def check_duplicate
-
returnObj = {}
-
if params[:friendly_name].blank?
-
returnObj['is_duplicated'] = 'false'
-
else
-
notification_group = @ssl_account.notification_groups.find_by_friendly_name(params[:friendly_name])
-
returnObj['is_duplicated'] = notification_group ?
-
(params[:ng_id] == '' ?
-
'true' :
-
(notification_group.id.to_s == params[:ng_id] ?
-
'false' : 'true'))
-
: 'false'
-
end
-
-
render :json => returnObj
-
end
-
-
def register_notification_group
-
if params[:format]
-
# Saving notification group info
-
notification_group = @ssl_account.notification_groups.includes(:notification_groups_subjects).where(ref: params[:format]).first
-
notification_group.friendly_name = params[:friendly_name] unless params[:friendly_name].blank?
-
notification_group.scan_port = params[:scan_port]
-
notification_group.notify_all = params[:notify_all] ? params[:notify_all] : false
-
notification_group.status = params[:status] ? params[:status] : false
-
else
-
# Saving notification group info
-
notification_group = NotificationGroup.new(
-
friendly_name: params[:friendly_name],
-
scan_port: params[:scan_port],
-
notify_all: params[:notify_all] ? params[:notify_all] : false,
-
ssl_account: @ssl_account,
-
status: params[:status] ? params[:status] : false
-
)
-
end
-
-
# Saving notification group triggers
-
if params[:notification_group_triggers]
-
params[:notification_group_triggers].uniq.sort{|a,b|a.to_i <=> b.to_i}.reverse.each_with_index do |rt, i|
-
notification_group.preferred_notification_group_triggers = rt.or_else(nil), ReminderTrigger.find(i+1)
-
end
-
end
-
-
unless notification_group.save
-
flash[:error] = "Some error occurs while saving notification group data. Please try again."
-
redirect_to new_notification_group_path(ssl_slug: @ssl_slug) and return unless params[:format]
-
redirect_to edit_notification_group_path(@ssl_slug, notification_group.id) and return
-
end
-
-
# Saving certificate order tags
-
if params[:cos_list]
-
current_tags = notification_group.certificate_orders.pluck(:id)
-
remove_tags = current_tags - params[:cos_list]
-
add_tags = params[:cos_list] - current_tags
-
-
# Remove old tags
-
notification_group.notification_groups_subjects.
-
where(subjectable_type: 'CertificateOrder', subjectable_id: remove_tags).destroy_all
-
-
# Add new tags
-
add_tags.each do |id|
-
notification_group.notification_groups_subjects.build(
-
subjectable_type: 'CertificateOrder', subjectable_id: id
-
).save
-
end
-
else
-
notification_group.notification_groups_subjects
-
.where(subjectable_type: 'CertificateOrder').destroy_all
-
end
-
-
# Saving subject tags
-
if params[:subjects_list]
-
parsed_params = parse_params(params[:subjects_list])
-
current_tags = notification_group.notification_groups_subjects
-
.where(subjectable_type: ['CertificateName', nil]).pluck(:domain_name, :subjectable_id)
-
.map{ |arr| arr[0].blank? ? arr[1].to_s : (arr[1].blank? ? arr[0] : (arr[0] + '---' + arr[1].to_s)) }
-
remove_tags = current_tags - parsed_params
-
add_tags = parsed_params - current_tags
-
-
# Remove old tags
-
remove_tags.each do |subject|
-
if subject.split('---').size == 1
-
if subject !~ /\D/
-
notification_group.notification_groups_subjects
-
.where(subjectable_type: 'CertificateName', subjectable_id: subject).destroy_all
-
else
-
notification_group.notification_groups_subjects.where(domain_name: subject).destroy_all
-
end
-
else
-
notification_group.notification_groups_subjects
-
.where(subjectable_type: 'CertificateName', subjectable_id: subject.split('---')[1]).destroy_all
-
end
-
end
-
-
# Add new tags
-
add_tags.each do |subject|
-
if subject.split('---').size == 1
-
if subject !~ /\D/
-
notification_group.notification_groups_subjects.build(
-
subjectable_type: 'CertificateName', subjectable_id: subject
-
).save
-
else
-
notification_group.notification_groups_subjects.build(
-
domain_name: subject
-
).save
-
end
-
else
-
notification_group.notification_groups_subjects.build(
-
domain_name: subject.split('---')[0],
-
subjectable_id: subject.split('---')[1],
-
subjectable_type: 'CertificateName'
-
).save
-
end
-
end
-
else
-
# Remove all domains for this notification group
-
notification_group.notification_groups_subjects.where(subjectable_type: ['CertificateName', nil]).destroy_all
-
end
-
-
# Saving contact tags
-
if params[:contacts_list]
-
parsed_params = parse_params(params[:contacts_list])
-
current_tags = notification_group.notification_groups_contacts.pluck(:email_address, :contactable_id)
-
.map{ |arr| arr[0].blank? ? arr[1].to_s : (arr[1].blank? ? arr[0] : (arr[0] + '---' + arr[1].to_s)) }
-
remove_tags = current_tags - parsed_params
-
add_tags = parsed_params - current_tags
-
-
# Remove old tags
-
remove_tags.each do |contact|
-
if contact.split('---').size == 1
-
if contact !~ /\D/
-
notification_group.notification_groups_contacts
-
.where(contactable_type: 'CertificateContact', contactable_id: contact).destroy_all
-
else
-
notification_group.notification_groups_contacts.where(email_address: contact).destroy_all
-
end
-
else
-
notification_group.notification_groups_contacts
-
.where(contactable_type: 'CertificateContact', contactable_id: contact.split('---')[1]).destroy_all
-
end
-
end
-
-
# Add new tags
-
add_tags.each do |contact|
-
if contact.split('---').size == 1
-
if contact !~ /\D/
-
notification_group.notification_groups_contacts.build(
-
contactable_type: 'CertificateContact', contactable_id: contact
-
).save
-
else
-
notification_group.notification_groups_contacts.build(
-
email_address: contact
-
).save
-
end
-
else
-
notification_group.notification_groups_contacts.build(
-
email_address: contact.split('---')[0],
-
contactable_id: contact.split('---')[1],
-
contactable_type: 'CertificateContact'
-
).save
-
end
-
end
-
else
-
# Remove all domains for this notification group
-
notification_group.notification_groups_contacts.destroy_all
-
end
-
-
# Saving schedule
-
if params[:schedule_type] == 'true'
-
current_schedules = notification_group.schedules.pluck(:schedule_type)
-
if current_schedules.include? 'Simple'
-
notification_group.schedules.last.update_attribute(:schedule_value, params[:schedule_simple_type])
-
else
-
notification_group.schedules.destroy_all
-
notification_group.schedules.build(
-
schedule_type: 'Simple',
-
schedule_value: params[:schedule_simple_type]
-
).save
-
end
-
else
-
current_schedules = notification_group.schedules.pluck(:schedule_type)
-
if current_schedules.include? 'Simple'
-
notification_group.schedules.destroy_all
-
end
-
-
# Weekday
-
current_schedules = notification_group.schedules.where(schedule_type: 'Weekday').pluck(:schedule_value)
-
if params[:weekday_type] == 'true'
-
unless current_schedules.include? 'All'
-
notification_group.schedules.where(schedule_type: 'Weekday').destroy_all
-
notification_group.schedules.build(
-
schedule_type: 'Weekday',
-
schedule_value: 'All'
-
).save
-
end
-
else
-
params[:weekday_custom_list] ||= []
-
new_weekdays = params[:weekday_custom_list] - current_schedules
-
old_weekdays = current_schedules - params[:weekday_custom_list]
-
-
notification_group.schedules.where(schedule_type: 'Weekday', schedule_value: old_weekdays).destroy_all
-
new_weekdays.each do |weekday|
-
notification_group.schedules.build(
-
schedule_type: 'Weekday',
-
schedule_value: weekday
-
).save
-
end
-
end
-
-
# Month
-
current_schedules = notification_group.schedules.where(schedule_type: 'Month').pluck(:schedule_value)
-
if params[:month_type] == 'true'
-
unless current_schedules.include? 'All'
-
notification_group.schedules.where(schedule_type: 'Month').destroy_all
-
notification_group.schedules.build(
-
schedule_type: 'Month',
-
schedule_value: 'All'
-
).save
-
end
-
else
-
params[:month_custom_list] ||= []
-
new_months = params[:month_custom_list] - current_schedules
-
old_months = current_schedules - params[:month_custom_list]
-
-
notification_group.schedules.where(schedule_type: 'Month', schedule_value: old_months).destroy_all
-
new_months.each do |month|
-
notification_group.schedules.build(
-
schedule_type: 'Month',
-
schedule_value: month
-
).save
-
end
-
end
-
-
# Day
-
current_schedules = notification_group.schedules.where(schedule_type: 'Day').pluck(:schedule_value)
-
if params[:day_type] == 'true'
-
unless current_schedules.include? 'All'
-
notification_group.schedules.where(schedule_type: 'Day').destroy_all
-
notification_group.schedules.build(
-
schedule_type: 'Day',
-
schedule_value: 'All'
-
).save
-
end
-
else
-
params[:day_custom_list] ||= []
-
new_days = params[:day_custom_list] - current_schedules
-
old_days = current_schedules - params[:day_custom_list]
-
-
notification_group.schedules.where(schedule_type: 'Day', schedule_value: old_days).destroy_all
-
new_days.each do |day|
-
notification_group.schedules.build(
-
schedule_type: 'Day',
-
schedule_value: day
-
).save
-
end
-
end
-
-
# Hour
-
current_schedules = notification_group.schedules.where(schedule_type: 'Hour').pluck(:schedule_value)
-
if params[:hour_type] == 'true'
-
unless current_schedules.include? 'All'
-
notification_group.schedules.where(schedule_type: 'Hour').destroy_all
-
notification_group.schedules.build(
-
schedule_type: 'Hour',
-
schedule_value: 'All'
-
).save
-
end
-
else
-
params[:hour_custom_list] ||= []
-
new_hours = params[:hour_custom_list] - current_schedules
-
old_hours = current_schedules - params[:hour_custom_list]
-
-
notification_group.schedules.where(schedule_type: 'Hour', schedule_value: old_hours).destroy_all
-
new_hours.each do |hour|
-
notification_group.schedules.build(
-
schedule_type: 'Hour',
-
schedule_value: hour
-
).save
-
end
-
end
-
-
# Minute
-
current_schedules = notification_group.schedules.where(schedule_type: 'Minute').pluck(:schedule_value)
-
if params[:minute_type] == 'true'
-
unless current_schedules.include? 'All'
-
notification_group.schedules.where(schedule_type: 'Minute').destroy_all
-
notification_group.schedules.build(
-
schedule_type: 'Minute',
-
schedule_value: 'All'
-
).save
-
end
-
else
-
params[:minute_custom_list] ||= []
-
new_minutes = params[:minute_custom_list] - current_schedules
-
old_minutes = current_schedules - params[:minute_custom_list]
-
-
notification_group.schedules.where(schedule_type: 'Minute', schedule_value: old_minutes).destroy_all
-
new_minutes.each do |minute|
-
notification_group.schedules.build(
-
schedule_type: 'Minute',
-
schedule_value: minute
-
).save
-
end
-
end
-
end
-
-
flash[:notice] = "Notification group has been updated successfully."
-
flash[:notice] = "New notification group has been created successfully." unless params[:format]
-
-
redirect_to notification_groups_path(ssl_slug: @ssl_slug) and return
-
end
-
-
def certificate_orders_domains_contacts
-
domains = []
-
domain_ids = []
-
contacts = []
-
contact_ids = []
-
-
if params['cos'] && params['cos'].size > 0
-
certificate_contents = @ssl_account.cached_certificate_orders.where(id: params['cos']).flatten.compact
-
.map(&:certificate_contents).flatten.compact
-
-
removed_dup_cns = remove_duplicate(certificate_contents.map(&:certificate_names)
-
.flatten.compact.map{ |cn| [cn.name, cn.id] })
-
domains.concat removed_dup_cns.keys
-
domain_ids.concat removed_dup_cns.values
-
-
removed_dup_ccts = remove_duplicate(certificate_contents.map(&:certificate_contacts)
-
.flatten.compact.map{ |cct| [cct.email, cct.id] })
-
contacts.concat removed_dup_ccts.keys
-
contact_ids.concat removed_dup_ccts.values
-
end
-
-
results = {}
-
results['domains'] = domains
-
results['domain_ids'] = domain_ids
-
results['contacts'] = contacts
-
results['contact_ids'] = contact_ids
-
-
render :json => results
-
end
-
-
private
-
def set_row_page
-
preferred_row_count = current_user.preferred_note_group_row_count
-
@per_page = params[:per_page] || preferred_row_count.or_else("10")
-
NotificationGroup.per_page = @per_page if NotificationGroup.per_page != @per_page
-
-
if @per_page != preferred_row_count
-
current_user.preferred_note_group_row_count = @per_page
-
current_user.save(validate: false)
-
end
-
-
@p = {page: (params[:page] || 1), per_page: @per_page}
-
end
-
-
def remove_duplicate(mArry)
-
result = {}
-
-
mArry.each do |arr|
-
if result[arr[0]].blank?
-
result[arr[0]] = arr[1].to_s
-
else
-
result[arr[0]] = (result[arr[0]] + '|' + arr[1].to_s).split('|').sort.join('|')
-
end
-
end
-
-
result
-
end
-
-
def parse_params(params)
-
result = []
-
-
params.each do |param|
-
if param !~ /\D/
-
result << param
-
else
-
if param.split('---').size == 1
-
param.split('|').size == 1 ? result << param : result.concat(param.split('|'))
-
else
-
if param.split('---')[1].split('|').size == 1
-
result << param
-
else
-
result.concat(param.split('---')[1].split('|').map{ |val| param.split('---')[0] + '---' + val })
-
end
-
end
-
end
-
end
-
-
result
-
end
-
-
def generate_slt_subjects
-
result = []
-
-
subjects = @notification_group.notification_groups_subjects
-
typed_subjects = subjects.where(["domain_name IS NOT ? and subjectable_id IS ?",
-
nil,
-
nil]).pluck(:domain_name)
-
result.concat(typed_subjects)
-
-
selected_subjects = remove_duplicate(
-
subjects.where.not(domain_name: nil, subjectable_id: nil).pluck(:domain_name, :subjectable_id)
-
).map{ |arr| arr[0] + '---' + arr[1].to_s }
-
result.concat(selected_subjects)
-
-
from_cert_orders = remove_duplicate(
-
@ssl_account.certificate_names
-
.where(id: subjects.where(domain_name: nil, subjectable_type: 'CertificateName')
-
.pluck(:subjectable_id))
-
.pluck(:name, :id)
-
).map{ |arr| arr[1].to_s }
-
-
result.concat(from_cert_orders)
-
-
result
-
end
-
-
def generate_slt_contacts
-
result = []
-
-
contacts = @notification_group.notification_groups_contacts
-
typed_contacts = contacts.where(["email_address IS NOT ? and contactable_id IS ?",
-
nil,
-
nil]).pluck(:email_address)
-
result.concat(typed_contacts)
-
-
selected_contacts = remove_duplicate(
-
contacts.where.not(email_address: nil, contactable_id: nil).pluck(:email_address, :contactable_id)
-
).map{ |arr| arr[0] + '---' + arr[1].to_s }
-
result.concat(selected_contacts)
-
-
slt_contact_ids = contacts.where(email_address: nil, contactable_type: 'CertificateContact')
-
.pluck(:contactable_id)
-
from_cert_orders = remove_duplicate(
-
@ssl_account.cached_certificate_orders.flatten.compact
-
.map(&:certificate_contents).flatten.compact
-
.map(&:certificate_contacts).flatten.compact
-
.select{ |contact| slt_contact_ids.include?(contact.id) }
-
.map{ |contact| [contact.email, contact.id.to_s] }
-
).map{ |arr| arr[1] }
-
-
result.concat(from_cert_orders)
-
-
result
-
end
-
-
def set_schedule_value
-
@schedule_simple_type = [
-
['Hourly', '1'],
-
['Daily (at midnight)', '2'],
-
['Weekly (on Sunday)', '3'],
-
['Monthly (on the 1st)', '4'],
-
['Yearly (on 1st Jan)', '5']
-
]
-
-
@schedule_weekdays = [
-
['Sunday', '0'], ['Monday', '1'], ['Tuesday', '2'], ['Wednesday', '3'],
-
['Thursday', '4'], ['Friday', '5'], ['Saturday', '6']
-
]
-
-
@schedule_months = [
-
['January', '1'], ['Febrary', '2'], ['March', '3'], ['April', '4'], ['May', '5'], ['June', '6'],
-
['July', '7'], ['August', '8'], ['September', '9'], ['October', '10'], ['November', '11'], ['December', '12']
-
]
-
-
@schedule_days = [
-
['1', '1'], ['2', '2'], ['3', '3'], ['4', '4'], ['5', '5'], ['6', '6'],
-
['7', '7'], ['8', '8'], ['9', '9'], ['10', '10'], ['11', '11'], ['12', '12'],
-
['13', '13'], ['14', '14'], ['15', '15'], ['16', '16'], ['17', '17'], ['18', '18'],
-
['19', '19'], ['20', '20'], ['21', '21'], ['22', '22'], ['23', '23'], ['24', '24'],
-
['25', '25'], ['26', '26'], ['27', '27'], ['28', '28'], ['29', '29'], ['30', '30'], ['31', '31']
-
]
-
-
@schedule_hours = [
-
['0', '0'], ['1', '1'], ['2', '2'], ['3', '3'], ['4', '4'], ['5', '5'], ['6', '6'],
-
['7', '7'], ['8', '8'], ['9', '9'], ['10', '10'], ['11', '11'], ['12', '12'],
-
['13', '13'], ['14', '14'], ['15', '15'], ['16', '16'], ['17', '17'], ['18', '18'],
-
['19', '19'], ['20', '20'], ['21', '21'], ['22', '22'], ['23', '23']
-
]
-
-
@schedule_minutes = [
-
['0', '0'], ['1', '1'], ['2', '2'], ['3', '3'], ['4', '4'], ['5', '5'], ['6', '6'],
-
['7', '7'], ['8', '8'], ['9', '9'], ['10', '10'], ['11', '11'], ['12', '12'],
-
['13', '13'], ['14', '14'], ['15', '15'], ['16', '16'], ['17', '17'], ['18', '18'],
-
['19', '19'], ['20', '20'], ['21', '21'], ['22', '22'], ['23', '23'], ['24', '24'],
-
['25', '25'], ['26', '26'], ['27', '27'], ['28', '28'], ['29', '29'], ['30', '30'],
-
['31', '31'], ['32', '32'], ['33', '33'], ['34', '34'], ['35', '35'], ['36', '36'],
-
['37', '37'], ['38', '38'], ['39', '39'], ['40', '40'], ['41', '41'], ['42', '42'],
-
['43', '43'], ['44', '44'], ['45', '45'], ['46', '46'], ['47', '47'], ['48', '48'],
-
['49', '49'], ['50', '50'], ['51', '51'], ['52', '52'], ['53', '53'], ['54', '54'],
-
['55', '55'], ['56', '56'], ['57', '57'], ['58', '58'], ['59', '59']
-
]
-
end
-
end
-
class OauthClientsController < ApplicationController
-
#before_filter :login_required
-
before_filter :get_client_application, :only => [:show, :edit, :update, :destroy]
-
-
def index
-
@client_applications = current_user.client_applications
-
@tokens = current_user.tokens.find :all, :conditions => 'oauth_tokens.invalidated_at is null and oauth_tokens.authorized_at is not null'
-
end
-
-
def new
-
@client_application = ClientApplication.new
-
end
-
-
def create
-
@client_application = current_user.client_applications.build(params[:client_application])
-
if @client_application.save
-
flash[:notice] = "Registered the information successfully"
-
redirect_to :action => "show", :id => @client_application.id
-
else
-
render :action => "new"
-
end
-
end
-
-
def show
-
end
-
-
def edit
-
end
-
-
def update
-
if @client_application.update_attributes(params[:client_application])
-
flash[:notice] = "Updated the client information successfully"
-
redirect_to :action => "show", :id => @client_application.id
-
else
-
render :action => "edit"
-
end
-
end
-
-
def destroy
-
@client_application.destroy
-
flash[:notice] = "Destroyed the client application registration"
-
redirect_to :action => "index"
-
end
-
-
private
-
def get_client_application
-
unless @client_application = current_user.client_applications.find(params[:id])
-
flash.now[:error] = "Wrong application id"
-
raise ActiveRecord::RecordNotFound
-
end
-
end
-
end
-
require 'oauth/controllers/provider_controller'
-
class OauthController < ApplicationController
-
include OAuth::Controllers::ProviderController
-
-
protected
-
# Override this to match your authorization page form
-
# It currently expects a checkbox called authorize
-
# def user_authorizes_token?
-
# params[:authorize] == '1'
-
# end
-
-
# should authenticate and return a user if valid password.
-
# This example should work with most Authlogic or Devise. Uncomment it
-
# def authenticate_user(username,password)
-
# user = User.find_by_email params[:username]
-
# if user && user.valid_password?(params[:password])
-
# user
-
# else
-
# nil
-
# end
-
# end
-
-
end
-
class OrdersController < ApplicationController
-
require 'cgi'
-
layout false, only: :invoice
-
include OrdersHelper
-
#resource_controller
-
helper_method :cart_items_from_model_and_id
-
before_filter :finish_reseller_signup, :only => [:new], if: "current_user"
-
before_filter :find_order, :only => [:show, :invoice, :update_invoice, :refund, :refund_merchant, :change_state,
-
:edit, :update, :transfer_order, :update_tags]
-
before_filter :find_scoped_order, :only => [:revoke]
-
before_filter :set_ssl_slug, only: :show
-
before_filter :set_prev_flag, only: [:create, :create_free_ssl, :create_multi_free_ssl]
-
before_filter :prep_certificate_orders_instances, only: [:create, :create_free_ssl]
-
before_filter :go_prev, :parse_certificate_orders, only: [:create_multi_free_ssl]
-
-
# before_filter :sync_aid_li_and_cart, :only=>[:create],
-
# :if=>Settings.sync_aid_li_and_cart
-
filter_access_to :all
-
filter_access_to :visitor_trackings, :filter_by_state, require: [:index]
-
filter_access_to :show, :update_invoice, attribute_check: true
-
before_filter :find_user, :only => [:user_orders]
-
before_filter :set_row_page, only: [:index, :search, :filter_by_state, :visitor_trackings]
-
before_filter :get_team_tags, only: [:index, :search]
-
-
def update_tags
-
if @order
-
@taggable = @order
-
get_team_tags
-
Tag.update_for_model(@taggable, params[:tags_list])
-
end
-
render json: {
-
tags_list: @taggable.nil? ? [] : @taggable.tags.pluck(:name)
-
}
-
end
-
-
def edit
-
-
end
-
-
def update
-
@order ||= Order.find(params[:id])
-
if @order.update_attributes(params[:order])
-
flash[:notice] = "Order ##{@order.reference_number} has been successfully updated."
-
redirect_to edit_order_path(@ssl_slug, @order)
-
else
-
render :edit
-
end
-
end
-
-
def transfer_order
-
from_team = @ssl_account
-
to_team = if current_user.is_system_admins?
-
SslAccount.find_by(acct_number: params[:target_team])
-
else
-
current_user.ssl_accounts.find_by(acct_number: params[:target_team])
-
end
-
-
if from_team && to_team
-
if @order.is_deposit?
-
SslAccount.migrate_deposit(from_team, to_team, @order, current_user)
-
else
-
SslAccount.migrate_orders(from_team, to_team, [@order.reference_number], current_user)
-
end
-
-
if to_team.orders.include?(@order)
-
flash[:notice] = "Successfully transfered order #{@order.reference_number} to team #{to_team.get_team_name}."
-
else
-
flash[:error] = "Something went wrong, please try again!"
-
end
-
else
-
flash[:error] = "You do not have access to team #{params[:target_team]}!"
-
end
-
redirect_to orders_path
-
end
-
-
# if the guid is in the URL, populate the browser cart cookie with the db shopping_cart record
-
# otherwise if the user is not logged in, populate the db shopping_cart with the contents stored in the browser cart cookie
-
def show_cart
-
@cart = ShoppingCart.find_by_guid(params[:id]) if params[:id]
-
if @cart # manually overwrite owned shopping_cart in favor of url specified
-
# cookies[ShoppingCart::CART_KEY] = {:value=>(@cart.content.blank? ? @cart.content : CGI.unescape(@cart.content)), :path => "/",
-
# :expires => Settings.cart_cookie_days.to_i.days.from_now}
-
if cookies[ShoppingCart::CART_KEY]=="delete"
-
cookies.delete(ShoppingCart::CART_KEY, domain: :all)
-
@cart.update_attribute(:content, nil)
-
end
-
set_cookie(ShoppingCart::CART_GUID_KEY,@cart.guid)
-
set_cookie(ShoppingCart::CART_KEY,@cart.content)
-
else
-
cart = cookies[ShoppingCart::CART_KEY]
-
guid = cookies[ShoppingCart::CART_GUID_KEY]
-
db_cart = ShoppingCart.find_by_guid(guid)
-
if current_user
-
if current_user.shopping_cart
-
guid=current_user.shopping_cart.guid
-
current_user.shopping_cart.update_attribute :content, cart
-
# elsif guid && db_cart
-
# db_cart.update_attributes content: cart, user_id: current_user.id
-
else # each user should 'own' a db_cart
-
guid=UUIDTools::UUID.random_create.to_s
-
current_user.create_shopping_cart(guid: guid, content: cart)
-
end
-
set_cookie(ShoppingCart::CART_GUID_KEY,guid)
-
elsif guid && db_cart #assume user is not logged in
-
db_cart.update_attribute(:content, cart)
-
else
-
guid=UUIDTools::UUID.random_create.to_s
-
set_cookie(ShoppingCart::CART_GUID_KEY,guid)
-
ShoppingCart.create(guid: guid, content: cart)
-
end
-
redirect_to show_cart_orders_path(id: guid)
-
end
-
setup_orders
-
end
-
-
def add_cart
-
cart = params[:cart]
-
guid = cookies[ShoppingCart::CART_GUID_KEY]
-
db_cart = ShoppingCart.find_by_guid(guid)
-
-
if current_user
-
if current_user.shopping_cart
-
guid = current_user.shopping_cart.guid
-
set_cookie(ShoppingCart::CART_GUID_KEY,guid)
-
-
# Get stored cart info
-
content = current_user.shopping_cart.content.blank? ? [] : JSON.parse(current_user.shopping_cart.content)
-
content = shopping_cart_content(content, cart)
-
current_user.shopping_cart.update_attribute :content, content.to_json
-
else # each user should 'own' a db_cart
-
guid = UUIDTools::UUID.random_create.to_s
-
set_cookie(ShoppingCart::CART_GUID_KEY,guid)
-
current_user.create_shopping_cart(guid: guid, content: [cart].to_json)
-
end
-
elsif guid && db_cart #assume user is not logged in
-
# Get stored cart info
-
content = db_cart.content.blank? ? [] : JSON.parse(db_cart.content)
-
content = shopping_cart_content(content, cart)
-
db_cart.update_attribute :content, content.to_json
-
else
-
guid = UUIDTools::UUID.random_create.to_s
-
set_cookie(ShoppingCart::CART_GUID_KEY,guid)
-
ShoppingCart.create(guid: guid, content: [cart].to_json)
-
end
-
-
render :json => {'guid' => guid}
-
end
-
-
def change_quantity_in_cart
-
returnObj = {}
-
-
# Getting Shopping Cart Info
-
if cookies[ShoppingCart::CART_GUID_KEY].blank?
-
returnObj['status'] = 'expired'
-
else
-
shopping_cart = ShoppingCart.find_by_guid(cookies[ShoppingCart::CART_GUID_KEY])
-
-
if shopping_cart
-
content = shopping_cart.content.blank? ? [] : JSON.parse(shopping_cart.content)
-
cart = cookies[ShoppingCart::CART_KEY].blank? ? [] : JSON.parse(cookies[ShoppingCart::CART_KEY])
-
-
# Changing the quantity if change the quantity
-
content = checkout_shopping_cart_content(content, cart)
-
shopping_cart.update_attribute :content, content.blank? ? nil : content.to_json
-
-
returnObj['status'] = 'success'
-
else
-
returnObj['status'] = 'no-exist'
-
end
-
end
-
-
render :json => returnObj
-
end
-
-
def add
-
add_to_cart @line_item = ActiveRecord::Base.find_from_model_and_id(param)
-
session[:cart_items].uniq!
-
-
respond_to do |format|
-
format.js { render :action => "cart_quantity.js.erb", :layout => false }
-
end
-
end
-
-
def new
-
if params[:reprocess_ucc] || params[:renew_ucc] || params[:ucc_csr_submit]
-
ucc_domains_adjust
-
elsif params[:smime_client_enrollment]
-
smime_client_enrollment
-
else
-
if params[:certificate_order] && !single_cert_no_limit_order?
-
@certificate = Certificate.for_sale.find_by_product(params[:certificate][:product])
-
unless params["prev.x".intern].nil?
-
redirect_to buy_certificate_url(@certificate) and return
-
end
-
-
if Settings.csr_domains_ui
-
managed_domains = params[:managed_domains]
-
additional_domains = ''
-
managed_domains.each do |domain|
-
additional_domains.concat(domain.gsub('csr-', '').gsub('validated-', '').gsub('manual-', '') + ' ')
-
end unless managed_domains.blank?
-
-
params[:certificate_order][:certificate_contents_attributes] = {}
-
params[:certificate_order][:certificate_contents_attributes]['0'.to_sym] = {}
-
params[:certificate_order][:certificate_contents_attributes]['0'.to_sym][:additional_domains] = additional_domains.strip
-
end
-
-
render(:template => "/certificates/buy",
-
:layout=>"application") and return unless certificate_order_steps
-
else
-
# Getting Shopping Cart Info
-
shopping_cart = ShoppingCart.find_by_guid(cookies[ShoppingCart::CART_GUID_KEY])
-
-
if shopping_cart
-
content = shopping_cart.content.blank? ? [] : JSON.parse(shopping_cart.content)
-
cart = cookies[ShoppingCart::CART_KEY].blank? ? [] : JSON.parse(cookies[ShoppingCart::CART_KEY])
-
-
# Changing the quantity if change the quantity
-
content = checkout_shopping_cart_content(content, cart)
-
shopping_cart.update_attribute :content, content.blank? ? nil : content.to_json
-
-
certificates_from_cookie
-
end
-
end
-
if current_user
-
if @certificate_orders && is_order_free?
-
create_multi_free_ssl
-
elsif ssl_account && ssl_account.no_limit
-
create_no_limit_order
-
elsif current_user.ssl_account.funded_account.cents > 0
-
redirect_to(is_current_order_affordable? ? confirm_funds_url(:order) :
-
allocate_funds_for_order_path(id: :order)) and return
-
end
-
end
-
end
-
end
-
-
def remove
-
unless session[:cart_items].nil?
-
@line_item = ActiveRecord::Base.find_from_model_and_id(param)
-
session[:cart_items].delete @line_item.model_and_id
-
end
-
-
respond_to do |format|
-
format.js { render :action => "remove_item.js.erb", :layout => false }
-
end
-
end
-
-
def empty_cart
-
@item_classes = session[:cart_items].collect{|cart_item| cart_item.split(/_(?=\d+$)/)[0]}.uniq!
-
session[:cart_items].clear
-
-
respond_to do |format|
-
format.js { render :action => "cart_quantity.js.erb", :layout => false }
-
end
-
end
-
-
def invoice
-
@orders = [@order]
-
invoices = !params[:start_date].blank? && !params[:end_date].blank?
-
-
if invoices
-
start = DateTime.parse(params[:start_date])
-
finish = DateTime.parse(params[:end_date])
-
@orders = (current_user.is_system_admins? ? @order.billable : current_user.ssl_account).orders.where(
-
state: 'paid',
-
created_at: start..finish,
-
description: 'SSL.com Certificate Order'
-
)
-
end
-
-
filename = if @orders.any? && @orders.count == 1
-
"ssl.com_invoice_ref_#{@orders.first.reference_number}"
-
elsif invoices
-
"ssl.com_invoices_#{start.strftime('%F')}_#{finish.strftime('%F')}"
-
else
-
"ssl.com_invoices_#{Date.today.strftime('%F')}"
-
end
-
-
respond_to do |format|
-
if @orders.any?
-
format.html { render pdf: filename }
-
else
-
flash[:error] = if invoices
-
'Zero orders found for this date range!'
-
else
-
'This order does not exist!'
-
end
-
format.html { redirect_to :back }
-
end
-
end
-
end
-
-
def update_invoice
-
cur_invoice = params[:monthly_invoice] || params[:daily_invoice]
-
-
found = if cur_invoice
-
Invoice.find_by(reference_number: cur_invoice[:invoice_ref])
-
else
-
Invoice.find_by(order_id: @order.id) if @order
-
end
-
update = found ? found : Invoice.new(params[:invoice])
-
-
no_errors = if found
-
update.update_attributes(
-
(cur_invoice ? cur_invoice : params[:invoice])
-
.keep_if {|k, v| !['order_id', 'invoice_ref'].include?(k)}
-
)
-
else
-
update.save
-
end
-
-
respond_to do |format|
-
if no_errors
-
format.json { render json: update, status: :ok }
-
else
-
format.json { render json: update.errors, status: :unprocessable_entity }
-
end
-
end
-
end
-
-
def lookup_discount
-
if current_user and !current_user.is_system_admins?
-
@discount=current_user.ssl_account.discounts.find_by_ref(params[:discount_code]) ||
-
Discount.viable.general.find_by_ref(params[:discount_code])
-
else
-
@discount=Discount.viable.general.find_by_ref(params[:discount_code])
-
end
-
rescue
-
end
-
-
def user_orders
-
@orders = current_user.orders
-
end
-
-
def studio_orders
-
@yahoo_grid = "yui-t1"
-
@line_items = @studio.line_items
-
end
-
-
def affiliate_orders
-
@yahoo_grid = "yui-t1"
-
@affiliate = Affiliate.find(params[:affiliate_id])
-
@line_items = @affiliate.line_items
-
end
-
-
def search
-
index
-
end
-
-
def revoke
-
if params[:revoke_all]
-
list = @order.cached_certificate_orders
-
list.each {|co| co.revoke!(params[:revoke_reason], current_user)}
-
-
SystemAudit.create(
-
owner: current_user,
-
target: @order,
-
notes: params[:revoke_reason],
-
action: 'Revoke all #{list.count} items(s) for order.'
-
)
-
flash[:notice] = "All #{list.count} order item(s) have been revoked."
-
else
-
co = CertificateOrder.unscoped.find_by(ref: params[:co_ref])
-
co.revoke!(params[:revoke_reason], current_user) if co
-
flash[:notice] = "Item ##{params[:co_ref]} has been revoked."
-
end
-
redirect_to order_path @order
-
end
-
-
def refund
-
@performed="#{params['cancel_only'] ? 'Cancelled ' : 'Refunded '} #{'partial ' if params["partial"]}order"
-
unless @order.blank?
-
unless params["partial"] # full refund
-
@target = @order
-
if params["return_funds"]
-
@full_refund_cents = @order.make_available_total
-
add_cents_to_funded_account(@full_refund_cents)
-
@performed << " and made #{Money.new(@full_refund_cents).format} available to customer."
-
end
-
params['cancel_only'] ? cancel_entire_order : @order.full_refund!
-
notify_ca(params["refund_reason"])
-
else # partial refunds or cancel line item
-
@target = @order.line_items.find {|li|li.sellable.try(:ref)==params["partial"]}
-
@target ||= @order.cached_certificate_orders.find { |co| co.ref==params["partial"] }
-
# certificate order has been cancelled but not refunded
-
@target ||= @order.certificate_orders.unscoped.find_by(ref: params[:partial])
-
-
refund_partial_amount(params) if params["return_funds"]
-
refund_partial_cancel(params) if params["cancel_only"]
-
end
-
SystemAudit.create(owner: current_user, target: @target, notes: params["refund_reason"], action: @performed)
-
end
-
redirect_to order_url(@order)
-
end
-
-
def notify_ca(notes)
-
@order.line_items.each { |li|
-
OrderNotifier.request_comodo_refund("refunds@ssl.com", li.sellable.external_order_number, notes).deliver if (defined? li.sellable.external_order_number)
-
OrderNotifier.request_comodo_refund("refunds@comodo.com", li.sellable.external_order_number,
-
notes).deliver if (defined?(li.sellable.external_order_number) && li.sellable.external_order_number)
-
OrderNotifier.request_comodo_refund("refunds@ssl.com", $1, notes).deliver if li.sellable.try(:notes) =~ /DV#(\d+)/
-
}
-
end
-
-
def refund_merchant
-
unless @order.blank?
-
@refunds = @order.refunds
-
if params[:type] == 'create'
-
if params[:cancel_cert_order]
-
co = CertificateOrder.find(params[:cancel_cert_order].to_i)
-
end
-
-
if params[:mo_ref]
-
mo = if current_user.is_system_admins?
-
Invoice.find_by(reference_number: params[:mo_ref])
-
else
-
current_user.ssl_account.invoices.find_by(reference_number: params[:mo_ref])
-
end
-
end
-
-
amount = Money.new(co ? @order.make_available_line(co, :merchant) : (params[:refund_amount].to_d * 100))
-
refund = @order.refund_merchant(amount.cents, params[:refund_reason], current_user.id)
-
last_refund = @order.refunds.last
-
-
if refund && last_refund && last_refund.successful?
-
flash[:notice] = "Successfully refunded merchant for amount #{amount.format}."
-
refund_merchant_for_co(co, amount) if co
-
refund_merchant_for_mo(mo, amount) if mo
-
@order.get_team_to_credit.funded_account.decrement!(:cents, last_refund.amount) if @order.is_deposit?
-
else
-
flash[:error] = "Refund for #{amount.format} has failed! #{last_refund.message}"
-
end
-
end
-
end
-
end
-
-
def refund_merchant_for_co(co, amount)
-
funded = @order.make_available_funded(co)
-
-
co.refund!
-
SystemAudit.create(
-
owner: current_user,
-
target: co,
-
notes: params["refund_reason"],
-
action: "Refunded partial amount for certificate order ##{co.ref}, merchant refund issued for #{amount.format}."
-
)
-
if funded > 0
-
add_cents_to_funded_account(funded)
-
flash[:notice] << " And made #{Money.new(funded).format} available to customer."
-
end
-
end
-
-
def refund_merchant_for_mo(mo, amount)
-
if mo.merchant_refunded?
-
mo.full_refund!
-
@order.full_refund! unless @order.fully_refunded?
-
else
-
mo.partial_refund!
-
@order.partial_refund!
-
end
-
-
SystemAudit.create(
-
owner: current_user,
-
target: mo,
-
notes: params["refund_reason"],
-
action: "#{@order.billable.get_invoice_label.capitalize} Invoice ##{mo.reference_number}, merchant refund issued for #{amount.format}."
-
)
-
end
-
-
def change_state
-
performed="order changed to #{params[:state]}"
-
unless @order.blank?
-
@order.send "#{params[:state]}!"
-
SystemAudit.create(owner: current_user, target: @order, action: performed)
-
notify_ca(params[:state]) if params[:state]=="charge_back"
-
end
-
redirect_to order_url(@order)
-
end
-
-
# GET /orders
-
# GET /orders.xml
-
def index
-
@search = params[:search] || ""
-
if is_sandbox? and @search.include?("is_test:true").blank?
-
@search << " is_test:true"
-
end
-
@unpaginated =
-
if !@search.blank?
-
if current_user.is_system_admins?
-
(@ssl_account.try(:orders) ? Order.unscoped{@ssl_account.try(:orders)} : Order.unscoped).where{state << ['payment_declined']}.search(@search)
-
else
-
current_user.ssl_account.orders.not_new.search(@search)
-
end
-
else
-
if current_user.is_system_admins?
-
(@ssl_account.try(:orders) ? Order.unscoped{@ssl_account.try(:orders)} : Order.unscoped).where{state << ['payment_declined']}.order("orders.created_at desc").not_test
-
else
-
current_user.ssl_account.orders.not_test
-
end
-
end.uniq
-
-
@orders = @unpaginated.paginate(@p)
-
-
respond_to do |format|
-
format.html { render :action => :index}
-
format.xml { render :xml => @orders }
-
end
-
end
-
-
def filter_by_state
-
states = [params[:id]]
-
@unpaginated =
-
if current_user.is_admin?
-
Order.unscoped{Order.includes(:line_items).where{state >> states}.order("orders.created_at desc")}
-
else
-
current_user.ssl_account.orders.unscoped{
-
current_user.ssl_account.cached_orders.includes(:line_items).where{state >> states}.order("orders.created_at desc")}
-
end
-
@orders = @unpaginated.paginate(@p)
-
-
respond_to do |format|
-
format.html { render :action=>:index}
-
format.xml { render :xml => @orders }
-
end
-
end
-
-
def visitor_trackings
-
@search = params[:search]
-
p = {:page => params[:page]}
-
-
@orders =
-
if !@search.blank?
-
Order.search(params[:search]).paginate(p)
-
else
-
Order.paginate(p)
-
end
-
end
-
-
# GET /orders/1
-
# GET /orders/1.xml
-
def show
-
@order.receipt=true
-
@taggable = @order
-
get_team_tags
-
if @order.description =~ /Deposit|Funded Account Withdrawal/i
-
@deposit = @order
-
elsif @order.line_items.count==1
-
@certificate_order = @order.cached_certificate_orders.uniq.last
-
else
-
certificates=[]
-
@certificate_orders = @order.cached_certificate_orders.uniq.map{|co|
-
unless certificates.include?(co.certificate)
-
certificates<<co.certificate
-
co
-
end}.compact
-
end
-
set_cookie(:acct,current_user.ssl_account.acct_number)
-
respond_to do |format|
-
if @order.line_items.count==1
-
format.html { render "/funded_accounts/success", :layout=>'application'}
-
else
-
format.html { render :action=>:show}
-
end
-
format.xml { render :xml => @order }
-
end
-
end
-
-
def create
-
@order = Order.new(params[:order])
-
@profile = @billing_profile = BillingProfile.new(params[:billing_profile])
-
too_many_declines = delay_transaction? && params[:payment_method] == 'credit_card'
-
unless current_user
-
@user = User.new(params[:user])
-
else
-
if(params[:funding_source])
-
@profile = BillingProfile.find(params[:funding_source])
-
end
-
end
-
respond_to do |format|
-
if order_reqs_valid?
-
if @certificate_orders
-
@order.add_certificate_orders(@certificate_orders)
-
else
-
@order=current_order
-
end
-
@credit_card = @profile.build_credit_card
-
end
-
apply_discounts(@order) #this needs to happen before the transaction but after the final incarnation of the order
-
if (@user ? @user.valid? : true) && !too_many_declines &&
-
order_reqs_valid? && purchase_successful?
-
save_user unless current_user
-
if @order.invoiced?
-
@order.invoice_denied_order(current_user.ssl_account)
-
else
-
@order.billing_profile = @profile
-
end
-
save_billing_profile unless params[:funding_source]
-
current_user.ssl_account.orders << @order
-
record_order_visit(@order)
-
@order.credit_affiliate(cookies)
-
if @certificate_orders
-
clear_cart
-
format.html { redirect_to order_path(@ssl_slug, @order) }
-
elsif @certificate_order
-
current_user.ssl_account.cached_certificate_orders << @certificate_order
-
@certificate_order.pay! @gateway_response.success? || @order.invoiced?
-
format.html { redirect_to edit_certificate_order_path(@ssl_slug, @certificate_order)}
-
end
-
else
-
if too_many_declines
-
flash[:error] = 'Too many failed attempts, please wait 1 minute to try again!'
-
end
-
format.html { render :action => "new" }
-
end
-
end
-
rescue Payment::AuthorizationError => error
-
flash.now[:error] = error.message
-
render :action => 'new'
-
end
-
-
# Order created for existing UCC certificate order on reprocess/rekey or renew,
-
# or initial CSR submit.
-
def ucc_domains_adjust_create
-
@reprocess_ucc = params[:order][:reprocess_ucc]
-
@renew_ucc = params[:order][:renew_ucc]
-
@ucc_csr_submit = params[:order][:ucc_csr_submit]
-
-
ucc_or_invoice_params
-
-
order_params = {
-
billing_profile_id: params[:funding_source],
-
amount: @target_amount,
-
cents: (@target_amount * 100).to_i,
-
description: Order::DOMAINS_ADJUSTMENT,
-
state: 'pending',
-
approval: 'approved',
-
notes: get_order_notes,
-
invoice_description: params[:order][:order_description],
-
wildcard_amount: params[:order][:wildcard_amount],
-
non_wildcard_amount: params[:order][:nonwildcard_amount],
-
}
-
-
@order = @reprocess_ucc ? ReprocessCertificateOrder.new(order_params) : Order.new(order_params)
-
@order.billable = @ssl_account
-
-
if @funded_amount > 0 && (@order_amount <= @funded_amount)
-
# All amount covered by credit from funded account
-
ucc_domains_adjust_funded(params)
-
else
-
# Pay full or partial payment by CC or Paypal
-
domains_adjust_hybrid_payment(params)
-
end
-
end
-
-
def create_free_ssl
-
@order = Order.new(params[:order])
-
unless current_user
-
@user = User.new(params[:user])
-
end
-
respond_to do |format|
-
if @certificate_orders
-
@order.add_certificate_orders(@certificate_orders)
-
else
-
@order=current_order
-
end
-
if @order.cents == 0 and @order.line_items.size > 0 and (@user ? @user.valid? : true)
-
save_user unless current_user
-
current_user.ssl_account.orders << @order
-
record_order_visit(@order)
-
@order.give_away!
-
if @certificate_orders
-
clear_cart
-
format.html { redirect_to @order }
-
elsif @certificate_order
-
current_user.ssl_account.cached_certificate_orders << @certificate_order
-
@certificate_order.pay! true
-
format.html { redirect_to edit_certificate_order_path(@certificate_order)}
-
end
-
else
-
format.html { render :action => "new" }
-
end
-
end
-
end
-
-
def create_multi_free_ssl
-
parse_certificate_orders
-
unless current_user
-
@user = User.new(params[:user])
-
end
-
respond_to do |format|
-
if @user and !@user.valid?
-
format.html { render action: "new" }
-
elsif @order.cents == 0 and @order.line_items.size > 0 and (@user || current_user)
-
save_user unless current_user
-
current_user.ssl_account.orders << @order
-
record_order_visit(@order)
-
@order.give_away!
-
if @certificate_order
-
@certificate_order.pay! true
-
return redirect_to edit_certificate_order_path(@certificate_order)
-
elsif @certificate_orders
-
current_user.ssl_account.orders << @order
-
clear_cart
-
flash[:notice] = "Order successfully placed. %s"
-
flash[:notice_item] = "Click here to finish processing your
-
ssl.com certificates.", credits_certificate_orders_path
-
format.html { redirect_to @order }
-
end
-
format.html { render :action => "success" }
-
else
-
if @order.line_items.size == 0
-
flash.now[:error] = "Cart is currently empty"
-
elsif @order.cents > 0
-
flash.now[:error] = "Cannot process non-free products"
-
end
-
if @certificate_order
-
return go_back_to_buy_certificate
-
else
-
format.html { redirect_to show_cart_orders_url }
-
end
-
end
-
end
-
end
-
-
def smime_client_enroll_create
-
ucc_or_invoice_params
-
smime_client_enrollment_base
-
if @funded_amount > 0 && (@order_amount <= @funded_amount)
-
# All amount covered by credit from funded account
-
smime_client_enrollment_funded
-
else
-
# Pay full or partial payment by CC or Paypal
-
smime_client_enrollment_hybrid_payment
-
end
-
end
-
-
private
-
-
def single_cert_no_limit_order?
-
ssl_account && ssl_account.no_limit && request.referer && request.referer.include?('certificates')
-
end
-
-
def add_cents_to_funded_account(cents)
-
@order.get_team_to_credit.funded_account.add_cents(cents)
-
end
-
# ============================================================================
-
# S/MIME OR CLIENT ENROLLMENT ORDER
-
# ============================================================================
-
def smime_client_enrollment
-
if current_user
-
smime_client_enrollment_base
-
if @ssl_account.invoice_required?
-
smime_client_enrollment_nolimit
-
else
-
render :smime_client_enrollment
-
end
-
else
-
redirect_to login_url and return
-
end
-
end
-
-
def smime_client_enrollment_base
-
@emails = params[:emails] || params[:smime_client_enrollment_order][:emails]
-
@emails = smime_client_parse_emails(@emails)
-
product = params[:certificate] || params[:smime_client_enrollment_order][:certificate]
-
@certificate = Certificate.find_by(product: product)
-
certificate_orders = smime_client_enrollment_items
-
-
@order = SmimeClientEnrollmentOrder.new(
-
state: 'new',
-
approval: 'approved',
-
invoice_description: smime_client_enrollment_notes(certificate_orders.count),
-
description: Order::S_OR_C_ENROLLMENT,
-
billable_id: certificate_orders.first.ssl_account.try(:id),
-
billable_type: 'SslAccount'
-
)
-
@order.add_certificate_orders(certificate_orders)
-
end
-
-
def smime_client_redirect_back
-
redirect_to new_order_path(@ssl_slug,
-
emails: params[:emails],
-
certificate: params[:certificate],
-
smime_client_enrollment: true
-
)
-
end
-
-
def smime_client_enrollment_hybrid_payment
-
if current_user && order_reqs_valid? && !@too_many_declines && purchase_successful?
-
save_billing_profile unless (params[:funding_source])
-
if @order.invoiced?
-
@order.invoice_denied_order(current_user.ssl_account)
-
else
-
@order.update(billing_profile_id: @profile.try(:id))
-
withdraw_funded_account((@funded_amount * 100).to_i) if @funded_amount > 0
-
end
-
record_order_visit(@order)
-
smime_client_enrollment_co_paid
-
smime_client_enrollment_registrants
-
smime_client_enrollment_validate
-
redirect_to order_path(@ssl_slug, @order)
-
else
-
if @too_many_declines
-
flash[:error] = 'Too many failed attempts, please wait 1 minute to try again!'
-
end
-
smime_client_redirect_back
-
end
-
rescue Payment::AuthorizationError => error
-
flash[:error] = error.message
-
smime_client_redirect_back
-
end
-
-
def smime_client_enrollment_funded
-
withdraw_amount = @order_amount < @funded_amount ? @order_amount : @funded_amount
-
withdraw_amount = (withdraw_amount * 100).to_i
-
withdraw_amount_str = Money.new(withdraw_amount).format
-
-
withdraw_funded_account(withdraw_amount)
-
-
if current_user && @order.valid? &&
-
((@ssl_account.funded_account.cents + withdraw_amount) == @funded_account_init)
-
@order.update(
-
billing_profile_id: nil,
-
deducted_from_id: nil,
-
state: 'paid'
-
)
-
record_order_visit(@order)
-
smime_client_enrollment_co_paid
-
smime_client_enrollment_registrants
-
smime_client_enrollment_validate
-
flash[:notice] = "Succesfully paid full amount of #{withdraw_amount_str} from funded account for order."
-
redirect_to order_path(@ssl_slug, @order)
-
else
-
flash[:error] = "Something went wrong, did not withdraw #{withdraw_amount_str} from funded account!"
-
smime_client_redirect_back
-
end
-
end
-
-
def smime_client_enrollment_nolimit
-
@order.state = 'invoiced'
-
@order.invoice_id = Invoice.get_or_create_for_team(@ssl_account).try(:id)
-
smime_client_enrollment_co_paid if @order.save
-
redirect_to order_path(@ssl_slug, @order)
-
end
-
# ============================================================================
-
# UCC Certificate reprocess/rekey helper methods for
-
# Invoiced Order: will be added to monthly invoice to be charged later
-
# Free Order: no additional domains, or fully covered by funded account credit
-
# Hybrid Payment Order: amount paid by BOTH funded account and (CC or Paypal)
-
# ============================================================================
-
def reprocess_ucc_redirect_back
-
redirect_to new_order_path(@ssl_slug,
-
co_ref: @certificate_order.ref, cc_ref: @certificate_content.ref, reprocess_ucc: true
-
)
-
end
-
-
def ucc_domains_adjust_funded(params)
-
withdraw_amount = @order_amount < @funded_amount ? @order_amount : @funded_amount
-
withdraw_amount = (withdraw_amount * 100).to_i
-
withdraw_amount_str = Money.new(withdraw_amount).format
-
-
withdraw_funded_account(withdraw_amount)
-
-
if current_user && @order.valid? &&
-
((@ssl_account.funded_account.cents + withdraw_amount) == @funded_account_init)
-
reprocess_ucc_order_free(params)
-
ucc_update_domain_counts
-
flash[:notice] = "Succesfully paid full amount of #{withdraw_amount_str} from funded account for order."
-
redirect_to edit_certificate_order_path(@ssl_slug, @certificate_order)
-
else
-
flash[:error] = "Something went wrong, did not withdraw #{withdraw_amount_str} from funded account!"
-
reprocess_ucc_redirect_back
-
end
-
end
-
-
def domains_adjust_hybrid_payment(params)
-
if current_user && order_reqs_valid? && !@too_many_declines && purchase_successful?
-
save_billing_profile unless (params[:funding_source])
-
if @order.invoiced?
-
@order.invoice_denied_order(current_user.ssl_account)
-
else
-
@order.billing_profile = @profile
-
@certificate_order.add_reproces_order @order
-
withdraw_funded_account((@funded_amount * 100).to_i) if @funded_amount > 0
-
end
-
record_order_visit(@order)
-
ucc_update_domain_counts
-
redirect_to edit_certificate_order_path(@ssl_slug, @certificate_order)
-
else
-
if @too_many_declines
-
flash[:error] = 'Too many failed attempts, please wait 1 minute to try again!'
-
end
-
reprocess_ucc_redirect_back
-
end
-
rescue Payment::AuthorizationError => error
-
flash[:error] = error.message
-
reprocess_ucc_redirect_back
-
end
-
-
def reprocess_ucc_order_free(params)
-
# On UCC reprocess, order is FREE if
-
# fully covered by funded account, or
-
# there were no additional domains from initial order
-
@order.billing_profile_id = nil
-
@order.deducted_from_id = nil
-
@order.state = 'paid'
-
@certificate_order.add_reproces_order @order
-
record_order_visit(@order)
-
@order.lock!
-
@order.save
-
# In case credits were used to cover the cost of order.
-
ucc_update_domain_counts
-
end
-
-
def create_no_limit_order
-
single_certificate = single_cert_no_limit_order?
-
ssl_account_id = ssl_account.id
-
-
if single_certificate
-
@certificate_order = certificates_from_cookie.last
-
@certificate_order.quantity = 1
-
@order = Order.new(
-
amount: @certificate_order.amount,
-
billable_id: ssl_account_id,
-
billable_type: 'SslAccount',
-
state: 'invoiced'
-
)
-
@order.add_certificate_orders([@certificate_order])
-
if @order.save
-
@certificate_order = @order.cached_certificate_orders.first
-
@certificate_order.update(
-
ssl_account_id: ssl_account_id, workflow_state: 'paid'
-
)
-
end
-
else
-
setup_orders
-
@order.billable_id = ssl_account_id
-
@order.billable_type = 'SslAccount'
-
if @order.save
-
@order.cached_certificate_orders.update_all(
-
ssl_account_id: ssl_account_id, workflow_state: 'paid'
-
)
-
end
-
clear_cart
-
end
-
-
@order.update(
-
state: 'invoiced',
-
invoice_id: Invoice.get_or_create_for_team(ssl_account_id).try(:id),
-
approval: 'approved',
-
invoice_description: Order::SSL_CERTIFICATE
-
)
-
record_order_visit(@order)
-
-
# flash[:notice] = "Order in the amount of #{@order.amount.format}
-
# will appear on the #{ssl_account.get_invoice_label} invoice."
-
if single_certificate
-
redirect_to edit_certificate_order_path(@ssl_slug, @certificate_order.ref)
-
else
-
redirect_to order_path(@ssl_slug, @order)
-
end
-
end
-
-
def add_to_payable_invoice(params)
-
invoice = Invoice.get_or_create_for_team(@ssl_account)
-
@order = current_order_reprocess_ucc if @reprocess_ucc
-
-
if @renew_ucc || @ucc_csr_submit
-
@order = @ssl_account.purchase(@certificate_order)
-
@order.cents = @amount * 100
-
@order.amount = @amount
-
end
-
@order.description = Order::DOMAINS_ADJUSTMENT
-
@order.state = 'invoiced'
-
@order.notes = get_order_notes
-
@order.invoice_id = invoice.id
-
@order.approval = 'approved'
-
@order.invoice_description = params[:order_description]
-
@order.wildcard_amount = params[:wildcard_amount]
-
@order.non_wildcard_amount = params[:nonwildcard_amount]
-
-
@certificate_order.add_reproces_order @order
-
ucc_update_domain_counts
-
record_order_visit(@order)
-
end
-
-
def ucc_domains_adjust
-
if current_user
-
@certificate_order = if current_user.is_system_admins?
-
CertificateOrder.find_by(ref: params[:co_ref])
-
else
-
current_user.ssl_account.cached_certificate_orders.find_by(ref: params[:co_ref])
-
end
-
@ssl_account = @certificate_order.try(:ssl_account)
-
@certificate_content = @certificate_order.certificate_contents.find_by(ref: params[:cc_ref])
-
-
@amount = if params[:renew_ucc] || params[:ucc_csr_submit]
-
params[:order_amount].to_f
-
else
-
@certificate_order.ucc_prorated_amount(@certificate_content, find_tier)
-
end
-
params[:reprocess_ucc] ? ucc_domains_adjust_reprocess : ucc_domains_adjust_other
-
else
-
redirect_to login_url and return
-
end
-
end
-
-
def ucc_domains_adjust_other
-
@renew_ucc = params[:renew_ucc]
-
@ucc_csr_submit = params[:ucc_csr_submit]
-
-
if @ssl_account.invoice_required? || @amount == 0
-
if @ssl_account.invoice_required? && @amount > 0 # Invoice Order, do not charge
-
add_to_payable_invoice(params)
-
# flash[:notice] = "The domains adjustment amount of #{@order.amount.format}
-
# will appear on the #{@ssl_account.get_invoice_label} invoice."
-
end
-
redirect_to edit_certificate_order_path(@ssl_slug, @certificate_order)
-
else
-
render 'ucc_domains_adjust'
-
end
-
end
-
-
def ucc_domains_adjust_reprocess
-
@reprocess_ucc = true
-
-
if @ssl_account.invoice_required? || @amount == 0
-
if @amount == 0 # Reprocess is free, no additional domains added
-
@order = ReprocessCertificateOrder.new(
-
amount: 0,
-
cents: 0,
-
description: Order::DOMAINS_ADJUSTMENT,
-
notes: reprocess_ucc_notes,
-
approval: 'approved'
-
)
-
@order.billable = @ssl_account
-
reprocess_ucc_order_free(params)
-
flash[:notice] = "This UCC certificate reprocess is free due to no additional domains."
-
end
-
-
if @ssl_account.invoice_required? && @amount > 0 # Invoice Order, do not charge
-
add_to_payable_invoice(params)
-
# flash[:notice] = "This UCC reprocess in the amount of #{Money.new(@amount).format}
-
# will appear on the #{@ssl_account.get_invoice_label} invoice."
-
end
-
redirect_to edit_certificate_order_path(@ssl_slug, @certificate_order)
-
else
-
render 'ucc_domains_adjust'
-
end
-
end
-
-
def set_row_page
-
preferred_row_count = current_user.preferred_order_row_count
-
@per_page = params[:per_page] || preferred_row_count.or_else("10")
-
-
if @per_page != preferred_row_count
-
current_user.preferred_order_row_count = @per_page
-
current_user.save(validate: false)
-
end
-
-
@p = {page: (params[:page] || 1), per_page: @per_page}
-
end
-
-
# admin user refunds line item
-
def refund_partial_amount(params)
-
refund_amount = @order.make_available_line(@target)
-
all_refunded = @order.line_items.select{|li|li.sellable.try("refunded?")}.count == @order.line_items.count
-
refund_amount_f = Money.new(refund_amount).format
-
-
add_cents_to_funded_account(refund_amount)
-
@performed << " and made #{refund_amount_f} available to customer"
-
-
# at least 1 lineitem needs to remain unrefunded or refunded amount is less than order total
-
if all_refunded || (@order.cents <= refund_amount)
-
@order.full_refund!
-
else
-
@order.partial_refund!(params["partial"], refund_amount)
-
end
-
if (@target.is_a?(LineItem) && @target.sellable.refunded?) || (@target.is_a?(CertificateOrder) && @target.refunded?)
-
flash[:notice] = "Line item was successfully credited for #{refund_amount_f}."
-
end
-
end
-
-
# admin user cancels line item
-
def refund_partial_cancel(params)
-
if @order.line_items.count == 1 #order has only one item, cencel entire order
-
@target = @order
-
cancel_entire_order
-
else
-
@performed = "Cancelled partial order #{@target.sellable.ref}, credit or refund were NOT issued."
-
@target.sellable.cancel! @target
-
end
-
end
-
-
# admin user cancels entire order and all of it's line items
-
def cancel_entire_order
-
@performed = "Cancelled entire order #{@target.reference_number}, credit or refund were NOT issued."
-
@target.cancel! unless @target.canceled?
-
if @target.canceled? && @target.invoice
-
@target.update(invoice_id: nil)
-
end
-
end
-
-
def certificate_order_steps
-
certificate_order=CertificateOrder.new(params[:certificate_order])
-
@certificate_order=Order.setup_certificate_order(certificate: @certificate, certificate_order: certificate_order)
-
determine_eligibility_to_buy(@certificate, certificate_order)
-
if instance_variable_get("@#{CertificateOrder::RENEWING}")
-
@certificate_order.renewal_id=instance_variable_get("@#{CertificateOrder::RENEWING}").id
-
end
-
@certificate_order.valid?
-
end
-
-
def find_order
-
@order = Order.unscoped{Order.find_by_reference_number(params[:id])}
-
end
-
-
def find_scoped_order
-
@order = (current_user.is_system_admins? ? Order : current_user.orders).find_by_reference_number(params[:id])
-
end
-
-
def checkout_shopping_cart_content(content, cart)
-
new_contents = []
-
# Check to be same the quantity
-
cart.each do |cookie|
-
same = content.detect{|cont| cont[ShoppingCart::LICENSES] == cookie[ShoppingCart::LICENSES] &&
-
!cont[ShoppingCart::DOMAINS].blank? && !cookie[ShoppingCart::DOMAINS].blank? &&
-
cont[ShoppingCart::DOMAINS].split(Certificate::DOMAINS_TEXTAREA_SEPARATOR).size == cookie[ShoppingCart::DOMAINS].split(Certificate::DOMAINS_TEXTAREA_SEPARATOR).size &&
-
(cont[ShoppingCart::DOMAINS].split(Certificate::DOMAINS_TEXTAREA_SEPARATOR) &
-
cookie[ShoppingCart::DOMAINS].split(Certificate::DOMAINS_TEXTAREA_SEPARATOR)).size == cont[ShoppingCart::DOMAINS].split(Certificate::DOMAINS_TEXTAREA_SEPARATOR).size &&
-
cont[ShoppingCart::DURATION] == cookie[ShoppingCart::DURATION] &&
-
cont[ShoppingCart::PRODUCT_CODE] == cookie[ShoppingCart::PRODUCT_CODE] &&
-
cont[ShoppingCart::SUB_PRODUCT_CODE] == cookie[ShoppingCart::SUB_PRODUCT_CODE] &&
-
cont[ShoppingCart::RENEWAL_ORDER] == cookie[ShoppingCart::RENEWAL_ORDER] &&
-
cont[ShoppingCart::AFFILIATE] == cookie[ShoppingCart::AFFILIATE]
-
}
-
-
same[ShoppingCart::QUANTITY] = cookie[ShoppingCart::QUANTITY].to_i if !same.blank? &&
-
same[ShoppingCart::QUANTITY].to_i != cookie[ShoppingCart::QUANTITY].to_i
-
-
new_contents << (same.blank? ? cookie : same)
-
end
-
new_contents = '' if new_contents.size == 0
-
-
return new_contents
-
end
-
-
def shopping_cart_content(content, cart)
-
match = true
-
idx = -1
-
-
# Check to exist same info
-
content.each_with_index do |cookie, i|
-
match = true
-
cookie.keys.each do |key|
-
if key != ShoppingCart::QUANTITY && key != ShoppingCart::AFFILIATE && cookie[key] != cart[key]
-
match = false
-
break
-
end
-
end
-
-
if match
-
idx = i
-
break
-
end
-
end
-
-
# Update content based on existing same one.
-
if idx == -1
-
cart[ShoppingCart::QUANTITY] = 1
-
if content.kind_of?(Array)
-
content << cart
-
else
-
content = [cart]
-
end
-
else
-
content[idx][ShoppingCart::QUANTITY] = content[idx][ShoppingCart::QUANTITY].to_i + 1
-
end
-
-
return content
-
end
-
end
-
class OtherPartyValidationRequestsController < ApplicationController
-
respond_to :json, only: :create
-
respond_to :html, only: :show
-
before_filter :require_user, only: :show
-
#filter_access_to :all
-
-
def create
-
@other_party_validation_request =
-
OtherPartyValidationRequest.new(params[:other_party_validation_request])
-
@other_party_validation_request.user = current_user
-
@other_party_validation_request.save
-
respond_with @other_party_validation_request
-
end
-
-
def show
-
@other_party_validation_request = OtherPartyValidationRequest.find_by_identifier(params[:id])
-
if @other_party_validation_request && @other_party_validation_request.allowed(current_user.email)
-
@certificate_order = @other_party_validation_request.other_party_requestable
-
render 'validations/edit'
-
else
-
permission_denied
-
end
-
end
-
end
-
class PasswordResetsController < ApplicationController
-
before_filter :require_no_user
-
before_filter :find_dup_login, :find_dup_email, only: [:create]
-
before_filter :load_user_using_perishable_token, :only => [:edit, :update]
-
-
def index
-
redirect_to new_password_reset_path
-
end
-
-
def edit
-
render
-
end
-
-
def update
-
@user.password = params[:user][:password]
-
@user.password_confirmation = params[:user][:password_confirmation]
-
-
if @user.save
-
flash[:notice] = "Password successfully updated"
-
redirect_to account_url
-
else
-
render :action => :edit
-
end
-
end
-
-
def new
-
render
-
end
-
-
def create
-
if verify_recaptcha(response: params['g-recaptcha-response'])
-
unless params[:login].blank?
-
@user = User.find_by_login(params[:login])
-
if @user
-
@user.deliver_password_reset_instructions!
-
flash[:notice] =
-
"Instructions to reset your password have been emailed to you. Please check your email."
-
redirect_to login_url
-
else
-
flash[:notice] = "No user was found with that login"
-
render :action => :new
-
end
-
else
-
@user = User.find_by_email(params[:email])
-
if @user
-
@user.deliver_username_reminder!
-
flash[:notice] =
-
"Your username has been emailed to you. Please check your email."
-
redirect_to login_url
-
else
-
flash[:notice] = "No user was found with that email"
-
render :action => :new
-
end
-
end
-
else
-
flash[:notice] = "Are you human?"
-
render :action => :new
-
end
-
end
-
-
private
-
-
def load_user_using_perishable_token
-
@user = User.find_by_perishable_token(params[:id])
-
unless @user
-
flash[:notice] = <<-EOS
-
We're sorry, but we could not locate your account.
-
If you are having issues try copying and pasting the URL
-
from your email into your browser or restarting the
-
reset password process.
-
EOS
-
redirect_to login_url
-
end
-
end
-
end
-
class PaypalExpressController < ApplicationController
-
before_filter :assigns_gateway, :setup_orders
-
before_filter :find_ssl_account, only: [:make_deposit, :purchase]
-
include ActiveMerchant::Billing
-
include ApplicationHelper, OrdersHelper, PaypalExpressHelper, FundedAccountsHelper
-
-
def item_to_buy
-
params[:make_deposit] ? make_deposit : current_order
-
end
-
-
def make_deposit
-
account = current_user.ssl_account || User.new.build_ssl_account
-
account.purchase Deposit.new({amount: params[:amount],payment_method: 'paypal'})
-
end
-
-
def checkout
-
unless current_user
-
@user = User.new(params[:user])
-
if @user.valid?
-
save_user
-
else
-
respond_to do |format|
-
format.html { render "orders/new" }
-
end and return
-
end
-
end
-
total_as_cents, setup_purchase_params = get_setup_purchase_params(item_to_buy, request, params)
-
setup_response = @gateway.setup_purchase(total_as_cents, setup_purchase_params)
-
redirect_to @gateway.redirect_url_for(setup_response.token)
-
end
-
-
def review
-
if params[:token].nil?
-
redirect_to root_url, :notice => 'Woops! Something went wrong!'
-
return
-
end
-
-
gateway_response = @gateway.details_for(params[:token])
-
-
unless gateway_response.success?
-
redirect_to root_url, :notice => "Sorry! Something went wrong with the Paypal purchase. Here's what Paypal said: #{gateway_response.message}"
-
return
-
end
-
-
@order_info = get_order_info gateway_response, item_to_buy
-
end
-
-
def purchase
-
if params[:token].nil?
-
redirect_to orders_url, :notice => "Sorry! Something went wrong with the Paypal purchase. Please try again later."
-
return
-
end
-
if ::Rails.env.test?
-
UserSession.create(User.first, true)
-
current_user = Authorization.current_user = User.first
-
@ssl_account = current_user.ssl_account
-
end
-
set_order_type
-
paypal_details = @gateway.details_for(params[:token])
-
total_as_cents, purchase_params = get_purchase_params paypal_details, request, params
-
purchase = @gateway.purchase total_as_cents, purchase_params
-
-
if purchase.success?
-
discount = purchase_params[:items].select {|i| i[:name]=='Discount'}
-
params[:discount_code] = discount.first[:Number] if discount.any?
-
-
# you might want to destroy your cart here if you have a shopping cart
-
if purchase_params[:items][0][:name]=~/(deposit|reseller)/i
-
@deposit=@ssl_account.purchase Deposit.create({amount: total_as_cents, payment_method: 'paypal'})
-
@deposit.description = "Paypal Deposit"
-
@deposit.notes = "#paidviapaypal#{purchase.authorization}"
-
@deposit.deposit_mode=true
-
@deposit.mark_paid!
-
@ssl_account.funded_account.increment! :cents, total_as_cents
-
unless params[:deduct_order]=~/false/i
-
if initial_reseller_deposit?
-
@order = current_order
-
#get this before transaction so user cannot change the cookie, thus
-
#resulting in mismatched item purchased
-
immutable_cart_item = ResellerTier.find_by_label(@order.
-
line_items.first.sellable.label)
-
else
-
setup_orders
-
end
-
order_w_discount = discount.any? ? (@order.cents - discount.first[:amount].abs) : @order.cents
-
if @ssl_account.funded_account.cents >= order_w_discount
-
funded_account_credit(purchase_params)
-
@ssl_account.funded_account.decrement! :cents, (order_w_discount - @funded_deduct_amt)
-
@ssl_account.orders << @order
-
@order.finalize_sale(params: params, deducted_from: @deposit,
-
visitor_token: @visitor_token, cookies: cookies)
-
if initial_reseller_deposit?
-
@ssl_account.reseller.finish_signup immutable_cart_item
-
end
-
if @funded
-
@funded.update(notes: "Partial payment for order ##{@order.reference_number} ($#{@order.amount.to_s}).")
-
end
-
notice = "Your purchase is now complete!"
-
clear_cart
-
else
-
notice = "Uh oh, not enough funds to complete the purchase. Please deposit #{((@ssl_account.funded_account.cents - @order.cents)*0.01).to_money}"
-
end
-
end
-
else
-
@auth_code = "#paidviapaypal#{purchase.authorization}"
-
if @domains_adjustment
-
@certificate_order = @ssl_account.cached_certificate_orders.find_by(ref: params[:co_ref])
-
@certificate_content = @ssl_account.certificate_contents.find_by(ref: params[:cc_ref])
-
domains_adjustment_order(purchase_params)
-
funded_account_credit(purchase_params)
-
@order.notes += " #{@auth_code}"
-
@certificate_order.add_reproces_order @order
-
elsif params[:smime_client_order]
-
smime_client_enrollment_order(purchase_params)
-
funded_account_credit(purchase_params)
-
elsif params[:monthly_invoice]
-
@invoice = Invoice.find_by(reference_number: params[:invoice_ref])
-
setup_monthly_invoice_order(purchase_params)
-
funded_account_credit(purchase_params)
-
@order.notes += " #{@auth_code}"
-
else
-
setup_orders
-
@order.notes = @auth_code
-
end
-
@order.lock!
-
@ssl_account.orders << @order
-
@order.finalize_sale(
-
params: params,
-
deducted_from: @deposit,
-
visitor_token: @visitor_token,
-
cookies: cookies
-
)
-
notice = "Your purchase is now complete!"
-
billed_to_address(paypal_details) unless params[:monthly_invoice]
-
clear_cart
-
end
-
else
-
notice = "Woops. Something went wrong while we were trying to complete the purchase with Paypal. Btw, here's what Paypal said: #{purchase.message}"
-
end
-
-
if @domains_adjustment
-
flash[:notice] = "Succesfully paid for UCC domains adjustment order."
-
redirect_to edit_certificate_order_path(@ssl_slug, @certificate_order)
-
elsif params[:smime_client_order]
-
@order.update(state: 'paid') if @order.persisted? && @order.state == 'invoiced'
-
flash[:notice] = "Succesfully paid S/MIME or Client Enrollment."
-
redirect_to order_path(@ssl_slug, @order)
-
elsif params[:monthly_invoice]
-
flash[:notice] = "Succesfully paid for invoice #{@invoice.reference_number}."
-
redirect_to invoice_path(@ssl_slug, @invoice.reference_number)
-
else
-
redirect_to orders_url, notice: notice
-
end
-
end
-
-
private
-
-
def smime_client_enrollment_order(purchase_params)
-
@emails = params[:emails]
-
@emails = smime_client_parse_emails(@emails)
-
product = params[:certificate]
-
@certificate = Certificate.find_by(product: product)
-
certificate_orders = smime_client_enrollment_items
-
-
@order = SmimeClientEnrollmentOrder.new(
-
state: 'new',
-
approval: 'approved',
-
invoice_description: smime_client_enrollment_notes(certificate_orders.count),
-
description: Order::S_OR_C_ENROLLMENT,
-
billable_id: certificate_orders.first.ssl_account.try(:id),
-
billable_type: 'SslAccount',
-
notes: @auth_code
-
)
-
@order.add_certificate_orders(certificate_orders)
-
if @order.save
-
smime_client_enrollment_co_paid
-
smime_client_enrollment_registrants
-
smime_client_enrollment_validate
-
end
-
end
-
-
def domains_adjustment_order(purchase_params)
-
order_params = {
-
amount: Money.new(purchase_params[:subtotal]),
-
cents: purchase_params[:subtotal],
-
description: Order::DOMAINS_ADJUSTMENT,
-
state: 'pending',
-
approval: 'approved',
-
notes: get_order_notes,
-
invoice_description: params[:order_description],
-
wildcard_amount: params[:wildcard_amount],
-
non_wildcard_amount: params[:nonwildcard_amount]
-
}
-
@order = @reprocess_ucc ? ReprocessCertificateOrder.new(order_params) : Order.new(order_params)
-
@order.billable = @ssl_account
-
ucc_update_domain_counts
-
@order.save
-
end
-
-
def setup_monthly_invoice_order(purchase_params)
-
@order = Order.new(
-
amount: Money.new(purchase_params[:subtotal]),
-
cents: purchase_params[:subtotal],
-
description: @ssl_account.get_invoice_pmt_description,
-
state: 'pending',
-
approval: 'approved',
-
notes: order_invoice_notes
-
)
-
@order.billable = @ssl_account
-
@order.save
-
@invoice.update(order_id: @order.id, status: 'paid') if @order.persisted?
-
end
-
-
def billed_to_address(paypal_details)
-
attrs = paypal_details.params['PayerInfo']['Address']
-
if @order && @order.persisted?
-
Invoice.create(
-
order_id: @order.id,
-
first_name: attrs['Name'].split.first,
-
last_name: attrs['Name'].split.last,
-
address_1: attrs['Street1'],
-
address_2: attrs['Street2'],
-
city: attrs['CityName'],
-
state: attrs['StateOrProvince'],
-
postal_code: attrs['PostalCode'],
-
country: attrs['Country'],
-
)
-
end
-
end
-
-
def assigns_gateway
-
s = ::Rails.application.secrets
-
@gateway ||= PaypalExpressGateway.new(
-
login: s.paypal_username,
-
password: s.paypal_password,
-
signature: s.paypal_signature
-
)
-
end
-
-
def set_order_type
-
@reprocess_ucc = params[:reprocess_ucc]
-
@renew_ucc = params[:renew_ucc]
-
@ucc_csr_submit = params[:ucc_csr_submit]
-
@payable_invoice = params[:monthly_invoice]
-
@domains_adjustment = @reprocess_ucc || @renew_ucc || @ucc_csr_submit
-
end
-
-
def get_funded_account_amt(purchase_params)
-
@funded_exists = purchase_params[:items].find {|i| i[:name]=='Funded Account'}
-
@funded_deduct_amt = @funded_exists ? @funded_exists[:amount].abs : 0
-
end
-
-
def funded_account_credit(purchase_params)
-
get_funded_account_amt(purchase_params)
-
names = [
-
'Monthly Invoice Pmt',
-
'Reprocess UCC Cert',
-
'Renew UCC Cert',
-
'UCC Cert Adjustment',
-
'Deposit',
-
'S/MIME Client Enroll'
-
]
-
order_amount = purchase_params[:items].find {|i| names.include?(i[:name])}[:amount]
-
if @funded_exists && @funded_deduct_amt > 0
-
withdraw_funded_account(@funded_deduct_amt, order_amount)
-
end
-
end
-
end
-
class PhysicalTokensController < ApplicationController
-
before_action :set_certificate_order
-
before_action :set_physical_token, only: [:show, :update, :destroy, :edit, :activate]
-
before_action :require_user
-
filter_access_to :all
-
filter_access_to :activate, :require=>:read
-
-
def new
-
@physical_token = @certificate_order.physical_tokens.new
-
end
-
-
# POST /physical_tokens
-
# POST /physical_tokens.json
-
def create
-
@physical_token = @certificate_order.physical_tokens.new(physical_token_params)
-
-
if @physical_token.save
-
redirect_to certificate_order_path @certificate_order
-
else
-
format.html { render :action => "new" }
-
end
-
end
-
-
# PATCH/PUT /physical_tokens/1
-
# PATCH/PUT /physical_tokens/1.json
-
def update
-
if @physical_token.update(physical_token_params)
-
redirect_to certificate_order_path @certificate_order
-
else
-
format.html { render :action => "new" }
-
end
-
end
-
-
# DELETE /physical_tokens/1
-
# DELETE /physical_tokens/1.json
-
def destroy
-
@physical_token.soft_delete!
-
-
redirect_to certificate_order_path @certificate_order
-
end
-
-
def activate
-
if params[:serial]==@physical_token.serial_number
-
@physical_token.confirm_serial!
-
flash[:notice] = "Token #{@physical_token.name} serial number confirmed. PIN is #{@physical_token.activation_pin}"
-
else
-
flash[:error] = "Serial number is not valid for token '#{@physical_token.name}'"
-
end
-
redirect_to certificate_order_path @certificate_order
-
end
-
-
def edit
-
-
end
-
-
private
-
-
def set_certificate_order
-
@certificate_order = CertificateOrder.find_by_ref(params[:certificate_order_id])
-
end
-
-
def set_physical_token
-
@physical_token = PhysicalToken.active.find(params[:id])
-
end
-
-
def physical_token_params
-
params[:physical_token][:management_key] = '' if params[:physical_token][:manufacturer] == 'Gemalto' &&
-
!params[:physical_token][:management_key].blank?
-
-
params.require(:physical_token).permit(:certificate_order_id, :signed_certificate_id, :tracking_number,
-
:shipping_method, :activation_pin, :admin_pin, :manufacturer, :model_number, :serial_number, :name,
-
:management_key, :notes, :license)
-
end
-
end
-
class ProductsController < ApplicationController
-
layout 'application'
-
before_filter :find_product, only: [:show, :edit, :update, :admin_update]
-
-
def search
-
index
-
render action: :index
-
end
-
-
# GET /site_seals
-
# GET /site_seals.xml
-
def index
-
p = {:page => params[:page]}
-
@certificate_orders = find_certificate_orders.joins(:site_seal).
-
select('distinct certificate_orders.*').
-
where("site_seals.workflow_state NOT IN ('new', 'canceled', 'deactivated')").paginate(p)
-
# @site_seals = find_certificate_orders(includes: :site_seal).
-
# map(&:site_seal).uniq.select{|ss|!ss.is_disabled?}.paginate(p)
-
end
-
-
# GET /site_seals/1
-
# GET /site_seals/1.xml
-
def show
-
respond_to do |format|
-
format.html # show.html.erb
-
format.xml { render :xml => @product }
-
end
-
end
-
-
# GET /site_seals/new
-
# GET /site_seals/new.xml
-
def new
-
@site_seal = SiteSeal.new
-
-
respond_to do |format|
-
format.html # new.html.erb
-
format.xml { render :xml => @site_seal }
-
end
-
end
-
-
# POST /site_seals
-
# POST /site_seals.xml
-
def create
-
@site_seal = SiteSeal.new(params[:site_seal])
-
-
respond_to do |format|
-
if @site_seal.save
-
flash[:notice] = 'SiteSeal was successfully created.'
-
format.html { redirect_to(@site_seal) }
-
format.xml { render :xml => @site_seal, :status => :created, :location => @site_seal }
-
else
-
format.html { render :action => "new" }
-
format.xml { render :xml => @site_seal.errors, :status => :unprocessable_entity }
-
end
-
end
-
end
-
-
# PUT /site_seals/1
-
# PUT /site_seals/1.xml
-
def update
-
respond_to do |format|
-
if @site_seal.update_attributes(params[:site_seal])
-
format.html { redirect_to(@site_seal) }
-
format.js { render :json=>@site_seal.to_json}
-
format.xml { head :ok }
-
else
-
format.html { render :action => "edit" }
-
format.xml { render :xml => @site_seal.errors, :status => :unprocessable_entity }
-
format.js { render :json=> @site_seal.errors.to_json}
-
end
-
end
-
end
-
-
def admin_update
-
@co = CertificateOrder.find params[:certificate_order]
-
respond_to do |format|
-
#allows us to bypass attr_protected. note this is admin only function
-
@site_seal.assign_attributes params[:site_seal], without_protection: true
-
if @site_seal.save
-
notify_customer if params[:email_customer]
-
format.html { redirect_to(@site_seal) }
-
format.js { render :json=>@site_seal.to_json}
-
format.xml { head :ok }
-
else
-
format.html { render :action => "edit" }
-
format.xml { render :xml => @site_seal.errors, :status => :unprocessable_entity }
-
format.js { render :json=> @site_seal.errors.to_json}
-
end
-
end
-
end
-
-
def site_report
-
if @site_seal.blank? || @site_seal.is_disabled?
-
render :disabled, :layout=>"site_report"
-
else
-
render :site_report, :layout=>"site_report"
-
end
-
end
-
-
def artifacts
-
unless @site_seal.is_disabled?
-
render :artifacts, :layout=>"site_report"
-
else
-
render :disabled, :layout=>"site_report"
-
end
-
end
-
-
private
-
-
def notify_customer
-
@co.processed_recipients.map{|r|r.split(" ")}.flatten.uniq.each do |c|
-
if @site_seal.fully_activated?
-
OrderNotifier.site_seal_approve(c, @co).deliver if @co.certificate.is_server?
-
else
-
OrderNotifier.site_seal_unapprove(c, @co).deliver
-
end
-
end
-
end
-
-
def find_product
-
raise ActiveRecord::RecordNotFound unless @product = Product.find_by_serial(params[:id])
-
end
-
-
end
-
class ResellerTiersController < ApplicationController
-
before_filter :require_user, :only => [:edit,:new]
-
before_filter :require_admin, :only => [:edit,:new]
-
-
def show
-
@reseller_tier = ResellerTier.general.find_by_id(params[:id])
-
if @reseller_tier.blank? and current_user
-
tier = current_user.ssl_account.reseller.reseller_tier if current_user.ssl_account.reseller
-
@reseller_tier = tier if tier == ResellerTier.find_by_id(params[:id])
-
end
-
not_found and return if @reseller_tier.blank?
-
end
-
-
def show_popup
-
@reseller_tier = ResellerTier.find(params[:id])
-
@popup = true
-
render :action=>'show', :layout=>"tier_pricing_popup"
-
end
-
-
def index
-
end
-
-
def edit
-
end
-
-
def new
-
end
-
-
end
-
class RestfulApiController < ApplicationController
-
-
def docs_apply
-
-
end
-
-
end
-
class ScanLogsController < ApplicationController
-
before_action :find_ssl_account
-
before_action :set_row_page, only: [:index]
-
-
def index
-
@notification_group = @ssl_account.notification_groups.find(params[:notification_group_id])
-
@scan_history_list = @notification_group.scan_logs.order('created_at desc').paginate(@p)
-
end
-
-
private
-
def set_row_page
-
preferred_row_count = current_user.preferred_scan_log_row_count
-
@per_page = params[:per_page] || preferred_row_count.or_else("10")
-
ScanLog.per_page = @per_page if ScanLog.per_page != @per_page
-
-
if @per_page != preferred_row_count
-
current_user.preferred_scan_log_row_count = @per_page
-
current_user.save(validate: false)
-
end
-
-
@p = {page: (params[:page] || 1), per_page: @per_page}
-
end
-
end
-
class SignedCertificatesController < ApplicationController
-
before_filter :new_signed_certificate_from_params, :on=>:create
-
filter_access_to :all, :attribute_check=>true
-
filter_access_to :server_bundle, :pkcs7, :whm_zip, :nginx, :apache_zip, :amazon_zip, :download, :require=>:show
-
-
# DELETE /signed_certificates/1
-
# DELETE /signed_certificates/1.xml
-
def destroy
-
csr=@signed_certificate.csr
-
@signed_certificate.destroy
-
respond_to do |format|
-
format.html { redirect_to(signed_certificates_url) }
-
format.js {
-
in_line_editor = render_to_string(:inline =>
-
"<%= in_place_editor_field csr, :signed_certificate_by_text, {},
-
{:field_type => 'textarea', :textarea_rows => 10,
-
:textarea_cols => 30} %>", :locals => { :csr => csr })
-
render :update do |page|
-
page.replace_html 'show_signed_certificate', in_line_editor
-
end
-
}
-
format.xml { head :ok }
-
end
-
end
-
-
def revoke
-
@signed_certificate = SignedCertificate.find(params[:id])
-
@signed_certificate.revoke!(params[:revoke_reason])
-
-
if @signed_certificate.revoked?
-
cc = @signed_certificate.certificate_content
-
list = cc.signed_certificates.pluck(:status).uniq
-
if list.count == 1 && list.include?('revoked')
-
cc.revoke!
-
SystemAudit.create(
-
owner: current_user,
-
target: cc,
-
notes: "Revoked due to reason: #{params[:revoke_reason]}",
-
action: 'Revoked certificate content.'
-
)
-
end
-
-
SystemAudit.create(
-
owner: current_user,
-
target: @signed_certificate,
-
notes: "Revoked due to reason: #{params[:revoke_reason]}",
-
action: 'Revoked signed certificate.'
-
)
-
flash[:notice] = "Signed Certificate was successfully revoked."
-
else
-
flash[:error] = "Something went wrong, please try again!"
-
end
-
redirect_to certificate_order_path(@ssl_slug, @signed_certificate.certificate_order.ref)
-
end
-
-
# POST /signed_certificates/1
-
# POST /signed_certificates/1.xml
-
def create
-
@signed_certificate.csr = Csr.find(params[:csr_id])
-
respond_to do |format|
-
if @signed_certificate.save
-
SystemAudit.create(owner: current_user, target: @signed_certificate,
-
notes: "manually saved certificate",
-
action: "SignedCertificateController#create")
-
format.html {
-
flash[:notice] = 'Signed certificate was successfully created.'
-
redirect_to(@signed_certificate.certificate_order) }
-
format.xml { head :ok }
-
format.js { render(json: @signed_certificate, methods:
-
[:expiration_date_js, :created_at_js])}
-
else
-
format.html { render :action => "edit" }
-
format.xml { render :xml =>@signed_certificate.errors, :status => :unprocessable_entity }
-
format.js { render :json=>@signed_certificate.errors.to_json}
-
end
-
end
-
end
-
-
def server_bundle
-
@signed_certificate = SignedCertificate.find(params[:id])
-
send_file @signed_certificate.ca_bundle(is_windows: is_client_windows?), :type => 'text', :disposition => 'attachment',
-
:filename =>"#{@signed_certificate.nonidn_friendly_common_name}.ca-bundle"
-
end
-
-
def pkcs7
-
@signed_certificate = SignedCertificate.find(params[:id])
-
send_data @signed_certificate.to_pkcs7, :type => 'text', :disposition => 'attachment',
-
:filename =>"#{@signed_certificate.nonidn_friendly_common_name}.p7b"
-
end
-
-
def nginx
-
@signed_certificate = SignedCertificate.find(params[:id])
-
send_data @signed_certificate.to_nginx, :type => 'text', :disposition => 'attachment',
-
:filename =>"#{@signed_certificate.nonidn_friendly_common_name}.chained.crt"
-
end
-
-
def whm_zip
-
@signed_certificate = SignedCertificate.find(params[:id])
-
send_file @signed_certificate.zipped_whm_bundle(is_client_windows?), :type => 'text', :disposition => 'attachment',
-
:filename =>"#{@signed_certificate.nonidn_friendly_common_name}.zip"
-
end
-
-
def apache_zip
-
@signed_certificate = SignedCertificate.find(params[:id])
-
send_file @signed_certificate.zipped_apache_bundle(is_client_windows?), :type => 'text', :disposition => 'attachment',
-
:filename =>"#{@signed_certificate.nonidn_friendly_common_name}.zip"
-
end
-
-
def amazon_zip
-
@signed_certificate = SignedCertificate.find(params[:id])
-
send_file @signed_certificate.zipped_amazon_bundle(is_client_windows?), :type => 'text', :disposition => 'attachment',
-
:filename =>"#{@signed_certificate.nonidn_friendly_common_name}.zip"
-
end
-
-
def download
-
@signed_certificate = SignedCertificate.find(params[:id])
-
t=File.new(@signed_certificate.create_signed_cert_zip_bundle(
-
{components: true, is_windows: is_client_windows?}), "r")
-
send_file t.path, :type => 'application/zip', :disposition => 'attachment',
-
:filename => @signed_certificate.nonidn_friendly_common_name+'.zip'
-
t.close
-
end
-
-
protected
-
def new_signed_certificate_from_params
-
@signed_certificate = SignedCertificate.new(params[:signed_certificate])
-
@signed_certificate.email_customer=true if params[:email_customer]
-
end
-
end
-
class SiteChecksController < ApplicationController
-
respond_to :xml, :json
-
-
# GET /site_checks
-
# GET /site_checks.xml
-
def index
-
@site_checks = SiteCheck.all
-
-
respond_to do |format|
-
format.html # index.html.erb
-
format.xml { render :xml => @site_checks }
-
end
-
end
-
-
# GET /site_checks/1
-
# GET /site_checks/1.xml
-
def show
-
@site_check = SiteCheck.find(params[:id])
-
-
respond_to do |format|
-
format.html # show.html.erb
-
format.xml { render :xml => @site_check }
-
end
-
end
-
-
# GET /site_checks/new
-
# GET /site_checks/new.xml
-
def new
-
@site_check = SiteCheck.new
-
-
respond_to do |format|
-
format.html # new.html.erb
-
format.xml { render :xml => @site_check }
-
end
-
end
-
-
# GET /site_checks/1/edit
-
def edit
-
@site_check = SiteCheck.find(params[:id])
-
end
-
-
# POST /site_checks
-
# POST /site_checks.xml
-
def create
-
@site_checks=[]
-
if params[:site_check]
-
@site_checks << SiteCheck.create(params[:site_check])
-
else
-
params[:urls].gsub(/\s+/, "").split(/[,\n]/).each do |url|
-
@site_checks << SiteCheck.create(url: url)
-
end
-
end
-
end
-
-
# PUT /site_checks/1
-
# PUT /site_checks/1.xml
-
def update
-
@site_check = SiteCheck.find(params[:id])
-
-
respond_to do |format|
-
if @site_check.update_attributes(params[:site_checks])
-
format.html { redirect_to(@site_check, :notice => 'Site check was successfully updated.') }
-
format.xml { head :ok }
-
else
-
format.html { render :action => "edit" }
-
format.xml { render :xml => @site_check.errors, :status => :unprocessable_entity }
-
end
-
end
-
end
-
-
# DELETE /site_checks/1
-
# DELETE /site_checks/1.xml
-
def destroy
-
@site_check = SiteCheck.find(params[:id])
-
@site_check.destroy
-
-
respond_to do |format|
-
format.html { redirect_to(site_checks_url) }
-
format.xml { head :ok }
-
end
-
end
-
end
-
1
class SiteController < ApplicationController
-
1
respond_to :xml, :html, only: :sitemap
-
1
layout false, only: [:customers, :paid_cert_orders]
-
1
include ApplicationHelper
-
-
1
STANDARD_PAGES = %w(repository restful_api terms_of_use privacy_policy copyright about contact_us news
-
buy_now top_level_domains_tlds)
-
-
caches_action :index, expires_in: 1.year,
-
1
:cache_path => Proc.new { |c| c.params } unless Rails.env =~ /development/ || "is_sandbox?".to_sym
-
-
1
def index
-
(redirect_to login_url and return) if is_sandbox?
-
render action: "buy_now"
-
end
-
-
1
def subject_alternative_name
-
-
end
-
-
#def paid_cert_orders
-
# co = CertificateOrder.nonfree
-
# render :text => proc { |response, output|
-
# output.write "<table><thead><th>date</th><th>ref</th><th>domain</th><th>amount</th></thead>"
-
# co.each do |i|
-
# output.write("<tr>")
-
# output.write("<td>#{co.created_at.strftime("%b %d, %Y")}")
-
# output.write("<td>#{co.ref_num}")
-
# output.write("<td>#{co.csr.try :common_name}")
-
# output.write("<td>#{co.amount}")
-
# end
-
# }
-
#end
-
-
1
def sitemap
-
# we use online generators now so the dynamic code is kept for legacy purposes
-
#headers['Content-Type'] = 'application/xml'
-
#@items = Certificate.sitemap # sitemap is a named scope
-
#last_item = @items.last
-
#if stale?(:etag => last_item, :last_modified => last_item.updated_at.utc)
-
# render action: 'sitemap.xml'
-
#end
-
if request.subdomain==Reseller::SUBDOMAIN
-
render action: 'reseller_sitemap.xml', content_type: 'application/xml', layout: false
-
else
-
render action: 'sitemap.xml', content_type: 'application/xml', layout: false
-
end
-
end
-
end
-
class SiteSealsController < ApplicationController
-
layout 'application'
-
before_filter :find_site_seal, only: [:artifacts, :site_report, :edit, :update, :admin_update]
-
filter_access_to :all
-
filter_access_to :edit, :update, :admin_update, attribute_check: true
-
filter_access_to :artifacts, :details, :require=>:read
-
-
def search
-
index
-
render action: :index
-
end
-
-
# GET /site_seals
-
# GET /site_seals.xml
-
def index
-
p = {:page => params[:page]}
-
@certificate_orders = find_certificate_orders.joins(:site_seal).
-
select('distinct certificate_orders.*').
-
where("site_seals.workflow_state NOT IN ('new', 'canceled', 'deactivated')").paginate(p)
-
# @site_seals = find_certificate_orders(includes: :site_seal).
-
# map(&:site_seal).uniq.select{|ss|!ss.is_disabled?}.paginate(p)
-
end
-
-
# GET /site_seals/1
-
# GET /site_seals/1.xml
-
def show
-
@certificate_order = CertificateOrder.unscoped.includes(:site_seal).find_by_ref(params[:certificate_order_id])
-
@site_seal = @certificate_order.site_seal
-
-
respond_to do |format|
-
format.html # show.html.erb
-
format.xml { render :xml => @site_seal }
-
end
-
end
-
-
# GET /site_seals/new
-
# GET /site_seals/new.xml
-
def new
-
@site_seal = SiteSeal.new
-
-
respond_to do |format|
-
format.html # new.html.erb
-
format.xml { render :xml => @site_seal }
-
end
-
end
-
-
# POST /site_seals
-
# POST /site_seals.xml
-
def create
-
@site_seal = SiteSeal.new(params[:site_seal])
-
-
respond_to do |format|
-
if @site_seal.save
-
flash[:notice] = 'SiteSeal was successfully created.'
-
format.html { redirect_to(@site_seal) }
-
format.xml { render :xml => @site_seal, :status => :created, :location => @site_seal }
-
else
-
format.html { render :action => "new" }
-
format.xml { render :xml => @site_seal.errors, :status => :unprocessable_entity }
-
end
-
end
-
end
-
-
# PUT /site_seals/1
-
# PUT /site_seals/1.xml
-
def update
-
respond_to do |format|
-
if @site_seal.update_attributes(params[:site_seal])
-
format.html { redirect_to(@site_seal) }
-
format.js { render :json=>@site_seal.to_json}
-
format.xml { head :ok }
-
else
-
format.html { render :action => "edit" }
-
format.xml { render :xml => @site_seal.errors, :status => :unprocessable_entity }
-
format.js { render :json=> @site_seal.errors.to_json}
-
end
-
end
-
end
-
-
def admin_update
-
@co = CertificateOrder.find params[:certificate_order]
-
respond_to do |format|
-
#allows us to bypass attr_protected. note this is admin only function
-
@site_seal.assign_attributes params[:site_seal], without_protection: true
-
if @site_seal.save
-
notify_customer if params[:email_customer]
-
format.html { redirect_to(@site_seal) }
-
format.js { render :json=>@site_seal.to_json}
-
format.xml { head :ok }
-
else
-
format.html { render :action => "edit" }
-
format.xml { render :xml => @site_seal.errors, :status => :unprocessable_entity }
-
format.js { render :json=> @site_seal.errors.to_json}
-
end
-
end
-
end
-
-
def site_report
-
if @site_seal.blank? || @site_seal.is_disabled?
-
render :disabled, :layout=>"site_report"
-
else
-
render :site_report, :layout=>"site_report"
-
end
-
end
-
-
def artifacts
-
unless @site_seal.is_disabled?
-
render :artifacts, :layout=>"site_report"
-
else
-
render :disabled, :layout=>"site_report"
-
end
-
end
-
-
private
-
-
def notify_customer
-
@co.processed_recipients.map{|r|r.split(" ")}.flatten.uniq.each do |c|
-
if @site_seal.fully_activated?
-
OrderNotifier.site_seal_approve(c, @co).deliver if @co.certificate.is_server?
-
else
-
OrderNotifier.site_seal_unapprove(c, @co).deliver
-
end
-
end
-
end
-
-
def find_site_seal
-
@site_seal = SiteSeal.find_by_ref(params[:id])
-
end
-
-
end
-
class SslAccountsController < ApplicationController
-
before_filter :require_user, only: [:show, :edit, :edit_settings]
-
before_filter :find_ssl_account
-
filter_access_to :all, attribute_check: true
-
-
# GET /ssl_account/
-
def show
-
respond_to do |format|
-
format.html # show.html.erb
-
format.xml { render :xml => @ssl_account }
-
end
-
end
-
-
# GET /ssl_account/edit
-
def edit
-
if params[:url_slug] || params[:update_company_name]
-
@ssl_account = (current_user.is_system_admins? ? SslAccount : current_user.ssl_accounts).find(params[:id]) if params[:id]
-
end
-
end
-
-
# GET /ssl_account/edit_settings
-
def edit_settings
-
# Generate one for each version of U2F, currently only `U2F_V2`
-
@registration_requests = u2f.registration_requests
-
-
# Store challenges. We need them for the verification step
-
session[:challenges] = @registration_requests.map(&:challenge)
-
-
# Fetch existing Registrations from your db and generate SignRequests
-
key_handles = current_user.u2fs.pluck(:key_handle)
-
@sign_requests = u2f.authentication_requests(key_handles)
-
@u2fs = current_user.u2fs
-
@duo_account = current_user.ssl_account(:default_team).duo_account
-
-
@app_id = u2f.app_id
-
end
-
-
def update_ssl_slug
-
ssl_slug = params[:ssl_account][:ssl_slug].downcase
-
ssl = SslAccount.find params[:ssl_account][:id]
-
-
if ssl && SslAccount.ssl_slug_valid?(ssl_slug) && ssl.update(ssl_slug: ssl_slug)
-
flash[:notice] = "You have successfully changed your team url to https://#{Settings.portal_domain}/team/#{params[:ssl_account][:ssl_slug]}."
-
if current_user.is_system_admins?
-
redirect_to users_path
-
else
-
set_ssl_slug(@user)
-
redirect_to account_path(ssl_slug: @ssl_slug)
-
end
-
else
-
flash[:error] = "Please try again using a valid slug name. #{ssl.errors.full_messages.join(', ')}."
-
redirect_to edit_ssl_account_path(params[:ssl_account].merge(url_slug: true))
-
end
-
end
-
-
def validate_ssl_slug
-
respond_to do |format|
-
format.js {render json: {message: SslAccount.ssl_slug_valid?(params[:ssl_slug_name])}}
-
end
-
end
-
-
def update_company_name
-
ssl = (current_user.is_system_admins? ? SslAccount : current_user.ssl_accounts).find params[:ssl_account][:id]
-
if ssl && ssl.update(company_name: params[:ssl_account][:company_name])
-
flash[:notice] = "Company name has been successfully updated to #{ssl.company_name}"
-
redirect_to account_path(ssl_slug: @ssl_slug)
-
else
-
flash[:error] = "Company name has NOT been updated due to errors! #{ssl.errors.full_messages.join(', ')}"
-
redirect_to edit_ssl_account_path(params[:ssl_account].merge(update_company_name: true))
-
end
-
end
-
-
# PUT /ssl_account/
-
def update
-
if params[:billing_method]
-
update_billing_method
-
elsif params[:no_limit]
-
update_no_limit
-
elsif params[:epki_agreement]
-
update_epki_agreement
-
else
-
update_reseller_profile
-
end
-
end
-
-
def remove_u2f
-
resultObj = {}
-
if current_user
-
u2f = current_user.u2fs.find(params['u2f_device_id'])
-
if u2f
-
u2f.destroy
-
resultObj['u2f_device_id'] = u2f.id
-
else
-
resultObj['error'] = 'There is no data for selected U2f Token'
-
end
-
else
-
resultObj['error'] = ''
-
end
-
-
render json: resultObj
-
end
-
-
def register_u2f
-
resultObj = {}
-
if current_user
-
response = U2F::RegisterResponse.load_from_json(params[:u2f_response])
-
exist = current_user.u2fs.find_by_key_handle(response.key_handle)
-
-
if exist
-
resultObj['error'] = 'This U2F device has already been registered.';
-
else
-
begin
-
reg = u2f.register!(session[:challenges], response)
-
-
# save a reference to your database
-
current_user.u2fs.create!(nick_name: params['nick_name'],
-
certificate: reg.certificate,
-
key_handle: reg.key_handle,
-
public_key: reg.public_key,
-
counter: reg.counter)
-
rescue U2F::Error => e
-
resultObj['error'] = 'Unable to register: ' + e.class.name
-
ensure
-
session.delete(:challenges)
-
resultObj['created_at'] = current_user.u2fs.last.created_at.strftime("%b %d, %Y")
-
resultObj['u2f_device_id'] = current_user.u2fs.last.id
-
end
-
end
-
else
-
resultObj['error'] = ''
-
end
-
-
render json: resultObj
-
end
-
-
def register_duo
-
resultObj = {}
-
if(current_user.ssl_account(:default_team).duo_account)
-
current_user.ssl_account(:default_team).duo_account.update_attributes(params.except(:action, :controller))
-
else
-
current_user.ssl_account(:default_team).create_duo_account
-
current_user.ssl_account(:default_team).duo_account.update_attributes(params.except(:action, :controller))
-
end
-
render json: resultObj
-
end
-
-
# PUT /ssl_account/
-
def update_settings
-
if params[:reminder_notice_triggers]
-
params[:reminder_notice_triggers].uniq.sort{|a,b|a.to_i <=> b.to_i}.
-
reverse.each_with_index do |rt, i|
-
@ssl_account.preferred_reminder_notice_triggers = rt.or_else(nil),
-
ReminderTrigger.find(i+1)
-
end
-
end
-
-
respond_to do |format|
-
if @ssl_account.update_attributes(params[:ssl_account])
-
flash[:notice] = 'Account settings were successfully updated.'
-
-
format.html { redirect_to(account_path(ssl_slug: @ssl_slug)) }
-
format.xml { head :ok }
-
else
-
format.html { render :action => "edit_settings" }
-
format.xml { render :xml => @ssl_account.errors, :status => :unprocessable_entity }
-
end
-
end
-
end
-
-
#PUT /ssl_account/duo_enable
-
def duo_enable
-
@ssl_account.update_attribute(:duo_enabled, params['duo_enable'])
-
respond_to do |format|
-
format.js {render json: @user.to_json}
-
end
-
end
-
-
#PUT /ssl_account/duo_own_used
-
def duo_own_used
-
@ssl_account.update_attribute(:duo_own_used, params['duo_own_used'])
-
respond_to do |format|
-
format.js {render json: @user.to_json}
-
end
-
end
-
-
#PUT /ssl_account/set_2fa_type
-
def set_2fa_type
-
type = @ssl_account.sec_type == params['sec_type'] ? '' : params['sec_type']
-
@ssl_account.update_attribute(:sec_type, type)
-
respond_to do |format|
-
format.js {render json: @ssl_account.to_json}
-
end
-
end
-
-
def adjust_funds
-
amount=params["amount"].to_f*100
-
@ssl_account.funded_account.add_cents(amount)
-
SystemAudit.create(owner: current_user, target: @ssl_account.funded_account,
-
notes: "amount (in USD): #{amount.to_s}",
-
action: "FundedAccount#add_cents")
-
if current_user.is_system_admins?
-
redirect_to teams_user_path(current_user)
-
else
-
redirect_to admin_show_user_path(@ssl_account.get_account_owner)
-
end
-
end
-
-
private
-
-
def update_no_limit
-
if current_user.is_system_admins?
-
ssl_account = SslAccount.where(
-
'ssl_slug = ? OR acct_number = ?', params[:ssl_slug], params[:ssl_slug]
-
).first
-
ssl_account.update(no_limit: params[:no_limit])
-
setting_type = params[:no_limit] == 'false' ? 'OFF' : 'ON'
-
flash[:notice] = "Successfully turned #{setting_type} team #{params[:ssl_slug]} no-limit setting."
-
else
-
flash[:error] = "You are not authorized to perform this action."
-
end
-
redirect_to teams_user_path(current_user, page: (params[:page] || 1))
-
end
-
-
def update_epki_agreement
-
if current_user.is_system_admins?
-
ssl_account = SslAccount.where(
-
'ssl_slug = ? OR acct_number = ?', params[:ssl_slug], params[:ssl_slug]
-
).first
-
setting_type = params[:epki_agreement] == 'false' ? 'OFF' : 'ON'
-
ssl_account.update(
-
epki_agreement: (setting_type == 'OFF' ? nil : DateTime.now)
-
)
-
flash[:notice] = "Successfully turned #{setting_type} team #{params[:ssl_slug]} epki_agreement setting."
-
else
-
flash[:error] = "You are not authorized to perform this action."
-
end
-
redirect_to teams_user_path(current_user, page: (params[:page] || 1))
-
end
-
-
def update_billing_method
-
if current_user.is_system_admins?
-
ssl_account = SslAccount.where(
-
'ssl_slug = ? OR acct_number = ?', params[:ssl_slug], params[:ssl_slug]
-
).first
-
ssl_account.update(billing_method: params[:billing_method])
-
flash[:notice] = "Successfully updated team #{params[:ssl_slug]} to '#{params[:billing_method]}' billing."
-
else
-
flash[:error] = "You are not authorized to perform this action."
-
end
-
redirect_to teams_user_path(current_user, page: (params[:page] || 1))
-
end
-
-
def update_reseller_profile
-
if current_user.is_system_admins?
-
@ssl_account = Reseller.find(params[:ssl_account][:reseller_attributes][:id]).ssl_account
-
@ssl_slug = @ssl_account.to_slug
-
end
-
respond_to do |format|
-
if @ssl_account.update_attributes(params[:ssl_account])
-
flash[:notice] = 'Reseller profile information was successfully updated.'
-
format.html { redirect_to(account_path(ssl_slug: @ssl_slug)) }
-
format.xml { head :ok }
-
else
-
format.html { render :action => "edit" }
-
format.xml { render :xml => @ssl_account.errors, :status => :unprocessable_entity }
-
end
-
end
-
end
-
end
-
require 'open-uri'
-
require 'nokogiri'
-
require 'timeout'
-
-
class SurlsController < ApplicationController
-
before_filter :find_surl_by_identifier, only: [:show, :login]
-
before_filter :find_surl_by_guid, only: [:edit, :destroy, :update]
-
skip_before_filter :record_visit
-
after_filter :record_surl_visit, only: [:show]
-
filter_access_to :edit, :destroy, :update, attribute_check: true
-
filter_access_to :admin_index
-
-
# GET /surls
-
# GET /surls.xml
-
def index
-
p = {:page => params[:page]}
-
if current_user && current_user.is_admin?
-
@surls=Surl.paginate(p)
-
else
-
@surls=get_valid_surls(p)
-
end
-
@surl=Surl.new
-
end
-
-
def admin_index
-
p = {:page => params[:page]}
-
@surls=Surl.all.paginate(p)
-
render action: index
-
end
-
-
#POST /surl_login
-
def login
-
@tmp_surl = Surl.new(params[:surl])
-
@tmp_surl.set_access_restrictions = "1" #activates validations
-
if @tmp_surl.valid?
-
show
-
else
-
render action: "restricted", layout: "only_scripts_and_css"
-
end
-
end
-
-
# GET /surls/1
-
# GET /surls/1.xml
-
def show
-
@render_result=Surl::RENDERED
-
not_found and return if @surl.blank?
-
if @surl.username && @surl.password_hash && (@tmp_surl.blank? || !@surl.access_granted(@tmp_surl))
-
@tmp_surl.errors[:base]<< "permission denied: invalid username and/or password" unless @tmp_surl.blank?
-
render action: "restricted", layout: "only_scripts_and_css" and return
-
end
-
if !@surl.is_http? || !@surl.share ||
-
(@surl.uri=~Regexp.new("\\.(#{Surl::REDIRECT_FILES.join("|")})$", "i")) || Settings.disable_links_banner
-
@render_result=Surl::REDIRECTED
-
redirect_to @surl.uri
-
#elsif @surl.require_ssl && !request.ssl?
-
# @render_result=Surl::REDIRECTED
-
# redirect_to @surl.full_link
-
else
-
#disable until we can improve performance
-
if false #Malware.is_blacklisted?(@surl.uri)
-
@render_result=Surl::BLACKLISTED
-
render action: "blacklisted", layout: false
-
elsif %w(\.youtube\. \.paypal\. \.google\.).detect{|h|URI.parse(@surl.uri).host =~ Regexp.new(h, "i")}
-
#retries = Surl::RETRIES
-
begin
-
timeout(Surl::TIMEOUT_DURATION) do
-
#don't have time to finish this but should'
-
#inner_html = render_to_string(partial: "banner", layout: false)
-
#render inline: open(@surl.uri).read.sub(/(\<[^\/]*body[^\/]*?\>)/i, "\1#{inner_html}") #doc.to_html
-
###################
-
doc = Nokogiri::HTML(open(@surl.uri))
-
doc.encoding = 'UTF-8' if doc.encoding.blank?
-
head = doc.at_css "head"
-
base = Nokogiri::XML::Node.new "base", doc
-
base["href"]=@surl.uri
-
body = doc.at_css "body"
-
div_position = Nokogiri::XML::Node.new('div', doc)
-
div_position["style"] = "position: relative;"
-
body.children.each do |child|
-
child.parent = div_position
-
end
-
body.add_child(div_position)
-
div = Nokogiri::XML::Node.new "div", doc
-
div["style"] = "background:#fff;border:1px solid #999;margin:-1px -1px 0;padding:0;"
-
div.inner_html = render_to_string(partial: "banner", layout: false)
-
body.children.first.before(div)
-
head.children.first.before(base)
-
render(inline: doc.to_html) and return
-
end
-
#rescue OpenURI::HTTPError
-
# render status: 408
-
#rescue Timeout::Error
-
# retries-=1
-
# if retries < Surl::RETRIES
-
# render status: 408
-
# else
-
# retry
-
# end
-
rescue Exception=>e
-
logger.error("Error in SurlsController#show: #{e.message}")
-
@render_result=Surl::REDIRECTED
-
redirect_to @surl.uri and return
-
end
-
end
-
response.headers['X-Frame-Options'] = "SAMEORIGIN"
-
render(action: "show", layout: false) and return
-
end
-
end
-
-
# GET /surls/new
-
# GET /surls/new.xml
-
def new
-
@surl = Surl.new
-
end
-
-
# GET /surls/1/edit
-
def edit
-
render action: "edit"
-
end
-
-
# POST /surls
-
# POST /surls.xml
-
def create
-
@surl = Surl.new(params[:surl])
-
@surl.user=current_user unless current_user.blank?
-
@surl.save
-
if @surl.errors.blank?
-
add_link_to_cookie(@surl.guid)
-
@surl_row = render_to_string("_surl_row.html.haml", layout: false, locals: {surl: @surl})
-
end
-
respond_to do |format|
-
surl_js = @surl.errors.blank? ? @surl.to_json.chop+", \"row\": #{@surl_row.to_json}}" : @surl.errors.to_json
-
format.js {render(json: surl_js)}
-
end
-
end
-
-
# PUT /surls/1
-
# PUT /surls/1.xml
-
def update
-
respond_to do |format|
-
if @surl.update_attributes(params[:surl])
-
#would have liked to use the bottom link but the flash notice disappears by the time it hits the index action
-
format.html { redirect_to surls_root_path,
-
:notice=> "Link #{@surl.full_link} has been updated."}
-
#flash[:notice]="Link #{@surl.full_link} has been updated."
-
#index
-
#format.html { render action: "index" }
-
format.xml { head :ok }
-
else
-
format.html { render :action => "edit" }
-
format.xml { render :xml => @surl.errors, :status => :unprocessable_entity }
-
end
-
end
-
end
-
-
def status_204
-
render inline: "", status: 204
-
end
-
-
# DELETE /surls/1
-
# DELETE /surls/1.xml
-
def destroy
-
@surl.destroy
-
flash[:notice] = "Link #{@surl.full_link} has been deleted." if request.xhr?
-
-
respond_to do |format|
-
format.js { render text: @surl.to_json }
-
format.html { redirect_to surls_root_url(:subdomain=>Surl::SUBDOMAIN) }
-
end
-
end
-
-
def disclaimer
-
render action: 'disclaimer', layout: 'only_scripts_and_css'
-
end
-
-
private
-
-
def find_surl_by_guid
-
@surl = Surl.find_by_guid(params[:id])
-
end
-
-
def find_surl_by_identifier
-
@surl = Surl.first(:conditions => ['BINARY identifier = ?', params[:id]])
-
end
-
end
-
class UnsubscribesController < ApplicationController
-
# GET /unsubscribes
-
# GET /unsubscribes.xml
-
def index
-
@unsubscribes = Unsubscribe.all
-
-
respond_to do |format|
-
format.html # index.html.erb
-
format.xml { render :xml => @unsubscribes }
-
end
-
end
-
-
# GET /unsubscribes/1
-
# GET /unsubscribes/1.xml
-
def show
-
@unsubscribe = Unsubscribe.find(params[:id])
-
-
respond_to do |format|
-
format.html # show.html.erb
-
format.xml { render :xml => @unsubscribe }
-
end
-
end
-
-
# GET /unsubscribes/new
-
# GET /unsubscribes/new.xml
-
def new
-
@unsubscribe = Unsubscribe.new
-
-
respond_to do |format|
-
format.html # new.html.erb
-
format.xml { render :xml => @unsubscribe }
-
end
-
end
-
-
# GET /unsubscribes/1/edit
-
def edit
-
@unsubscribe = Unsubscribe.find_by_ref(params[:id])
-
@unsubscribe.enforce=true
-
end
-
-
# POST /unsubscribes
-
# POST /unsubscribes.xml
-
def create
-
@unsubscribe = Unsubscribe.new(params[:unsubscribe])
-
-
respond_to do |format|
-
if @unsubscribe.save
-
format.html { redirect_to(@unsubscribe, :notice => 'Unsubscribe was successfully created.') }
-
format.xml { render :xml => @unsubscribe, :status => :created, :location => @unsubscribe }
-
else
-
format.html { render :action => "new" }
-
format.xml { render :xml => @unsubscribe.errors, :status => :unprocessable_entity }
-
end
-
end
-
end
-
-
# PUT /unsubscribes/1
-
# PUT /unsubscribes/1.xml
-
def update
-
@unsubscribe = Unsubscribe.find(params[:id])
-
if params[:email]==@unsubscribe.email
-
@unsubscribe.update_attributes(params[:unsubscribe])
-
else
-
@unsubscribe.errors[:base] << "test"
-
end
-
-
respond_to do |format|
-
format.js {render(text: (@unsubscribe.errors.blank? && !@unsubscribe.new_record?) ?
-
@unsubscribe.to_json : @unsubscribe.errors.to_json)}
-
end
-
end
-
-
# DELETE /unsubscribes/1
-
# DELETE /unsubscribes/1.xml
-
def destroy
-
@unsubscribe = Unsubscribe.find(params[:id])
-
@unsubscribe.destroy
-
-
respond_to do |format|
-
format.html { redirect_to(unsubscribes_url) }
-
format.xml { head :ok }
-
end
-
end
-
end
-
class UserSessionsController < ApplicationController
-
before_filter :require_no_user, only: [:new]
-
before_filter :find_dup_login, only: [:create]
-
before_filter :require_user, only: [:destroy, :duo]
-
skip_before_filter :finish_reseller_signup, only: [:destroy]
-
skip_before_action :verify_authenticity_token
-
skip_before_action :verify_duo_authentication, only: [:new, :create, :destroy]
-
skip_before_action :require_no_authentication, only: [:duo_verify]
-
-
def new
-
@failed_count = 0
-
@user_session = UserSession.new
-
session[:duo_auth] = false
-
end
-
-
def show
-
if params[:login]
-
create
-
else
-
redirect_to action: :new
-
end
-
end
-
-
def user_login
-
result_obj = {}
-
key_handles = []
-
cart_and_u2fs=->{
-
@user_session = UserSession.new(params[:user_session].to_h)
-
-
if @user_session.save && !@user_session.user.is_disabled?
-
shopping_cart_to_cookie
-
# Fetch existing U2Fs from your db
-
key_handles = @user_session.user.u2fs.pluck(:key_handle)
-
end
-
}
-
-
if params[:user_session][:failed_count].to_i >= Settings.captcha_threshold.to_i
-
if verify_recaptcha(response: params[:user_session]['g-recaptcha-response'])
-
cart_and_u2fs.call
-
end
-
else
-
cart_and_u2fs.call
-
end
-
-
unless key_handles.empty?
-
# Generate SignRequests
-
result_obj['app_id'] = u2f.app_id
-
result_obj['sign_requests'] = u2f.authentication_requests(key_handles)
-
result_obj['challenge'] = u2f.challenge
-
-
# Store challenge. We need it for the verification step
-
session[:challenge] = result_obj['challenge']
-
end
-
-
result_obj['failed_count'] = params[:user_session][:failed_count]
-
-
render :json => result_obj
-
end
-
-
def create
-
if params["prev.x".intern]
-
#assume trying to login during checkout
-
if params[:certificate_order]
-
@certificate_order=CertificateOrder.new(params[:certificate_order])
-
@certificate_order.has_csr=true
-
if params["prev.x".intern]
-
render(:template => "/certificates/buy",
-
:layout=>"application")
-
end
-
else
-
redirect_to show_cart_orders_url and return
-
end
-
end
-
-
if current_user.blank?
-
@user_session = UserSession.new(params[:user_session].to_h)
-
else
-
if current_user.is_admin? && params[:login]
-
@user_session = UserSession.new((User.find_by_login params[:login]))
-
@user_session.id = :shadow
-
clear_cart
-
end
-
-
unless current_user.ssl_account.nil?
-
set_cookie(:acct,current_user.ssl_account.acct_number)
-
end
-
end
-
-
respond_to do |format|
-
@failed_count = params[:failed_count].to_i
-
-
if @user_session
-
if @user_session.save && !@user_session.user.is_disabled?
-
user = shopping_cart_to_cookie
-
-
flash[:notice] = "Successfully logged in." unless request.xhr?
-
format.js {render :json=>url_for_js(user)}
-
format.html {redirect_back_or_default account_path(user.ssl_account(:default_team) ?
-
user.ssl_account(:default_team).to_slug :
-
{})}
-
elsif @user_session.attempted_record && !@user_session.attempted_record.active?
-
flash[:notice] = "Your account has not been activated. %s"
-
flash[:notice_item] = "Click here to have the activation email resent to #{@user_session.attempted_record.email}.",
-
resend_activation_users_path(:login => @user_session.attempted_record.login)
-
@user_session.errors[:base] << ("please visit #{resend_activation_users_url(
-
:login => @user_session.attempted_record.login)} to have your activation notice resent")
-
-
log_failed_attempt(@user_session.user, params,flash[:notice])
-
format.html {render :action => :new}
-
format.js {render :json=>@user_session.errors}
-
elsif @user_session.user.blank? || (!@user_session.user.blank? && @user_session.user.is_admin_disabled?)
-
unless @user_session.user.blank?
-
if (!@user_session.user.blank? && @user_session.user.is_admin_disabled?)
-
flash.now[:error] = "Ooops, it appears this account has been disabled." unless request.xhr?
-
-
log_failed_attempt(@user_session.user, params,flash.now[:error])
-
@user_session.destroy
-
@user_session=UserSession.new
-
end
-
end
-
log_failed_attempt(@user_session.user, params,@user_session.errors.to_json)
-
format.html {render :action => :new}
-
format.js {render :json=>@user_session}
-
else
-
log_failed_attempt(params[:user_session][:login], params,flash.now[:error])
-
format.html {render :action => :new}
-
format.js {render :json=>@user_session.errors}
-
end
-
else
-
if params[:logout] == 'true'
-
if current_user.is_admin?
-
cookies.delete(ResellerTier::TIER_KEY)
-
cookies.delete(ShoppingCart::CART_GUID_KEY)
-
clear_cart
-
end
-
cookies.delete(:acct)
-
current_user_session.destroy
-
Authorization.current_user=nil
-
flash[:error] = "Unable to sign with U2F." unless params[:user]
-
-
@user_session = UserSession.new(params[:user_session].to_h)
-
-
format.html {render :action => :new}
-
format.js {render :json=>@user_session}
-
else
-
@user_session = current_user_session
-
-
if current_user.is_duo_required?
-
flash[:notice] = "Duo 2-factor authentication setup." unless request.xhr?
-
format.js {render :json=>url_for_js(current_user)}
-
format.html {redirect_to(duo_user_session_url)}
-
else
-
if current_user.ssl_account(:default_team).sec_type == 'duo'
-
if current_user.ssl_account(:default_team).duo_enabled && (Settings.duo_auto_enabled || Settings.duo_custom_enabled) && current_user.duo_enabled
-
flash[:notice] = "Duo 2-factor authentication setup." unless request.xhr?
-
else
-
flash[:notice] = "Successfully logged in." unless request.xhr?
-
end
-
format.js {render :json=>url_for_js(current_user)}
-
if current_user.ssl_account(:default_team).duo_enabled && (Settings.duo_auto_enabled || Settings.duo_custom_enabled) && current_user.duo_enabled
-
format.html {redirect_to(duo_user_session_url)}
-
else
-
session[:duo_auth] = true
-
format.html {redirect_back_or_default account_path(current_user.ssl_account(:default_team) ? current_user.ssl_account(:default_team).to_slug : {})}
-
end
-
elsif current_user.ssl_account(:default_team).sec_type == 'u2f'
-
session[:duo_auth] = true
-
if params['u2f_response'].blank?
-
flash[:notice] = "Successfully logged in." unless request.xhr?
-
format.js {render :json=>url_for_js(current_user)}
-
format.html {redirect_back_or_default account_path(current_user.ssl_account(:default_team) ? current_user.ssl_account(:default_team).to_slug : {})}
-
else
-
response = U2F::SignResponse.load_from_json(params[:u2f_response])
-
reg_u2f = current_user.u2fs.find_by_key_handle(response.key_handle) if response.key_handle
-
-
unless reg_u2f
-
flash[:notice] = "Successfully logged in." unless request.xhr?
-
-
format.js {render :json=>url_for_js(current_user)}
-
format.html {redirect_back_or_default account_path(current_user.ssl_account(:default_team) ?
-
current_user.ssl_account(:default_team).to_slug :
-
{})}
-
end
-
-
begin
-
u2f.authenticate!(
-
session[:challenge],
-
response,
-
Base64.decode64(reg_u2f.public_key),
-
reg_u2f.counter
-
)
-
-
reg_u2f.update(counter: response.counter)
-
rescue U2F::Error => e
-
# Log out to protect hack.
-
if current_user.is_admin?
-
cookies.delete(ResellerTier::TIER_KEY)
-
cookies.delete(ShoppingCart::CART_GUID_KEY)
-
clear_cart
-
end
-
cookies.delete(:acct)
-
current_user_session.destroy
-
Authorization.current_user=nil
-
flash[:error] = "Unable to authenticate with U2F: " + e.class.name unless params[:user]
-
-
@user_session = UserSession.new(params[:user_session].to_h)
-
format.html {render :action => :new}
-
format.js {render :json=>@user_session.errors}
-
ensure
-
session.delete(:challenge)
-
end
-
-
flash[:notice] = "Successfully logged in." unless request.xhr?
-
-
format.js {render :json=>url_for_js(current_user)}
-
format.html {redirect_back_or_default account_path(current_user.ssl_account(:default_team) ?
-
current_user.ssl_account(:default_team).to_slug :
-
{})}
-
end
-
else
-
session[:duo_auth] = true;
-
flash[:notice] = "Successfully logged in." unless request.xhr?
-
format.js {render :json=>url_for_js(current_user)}
-
format.html {redirect_back_or_default account_path(current_user.ssl_account(:default_team) ? current_user.ssl_account(:default_team).to_slug : {})}
-
end
-
end
-
end
-
end
-
end
-
end
-
-
def duo
-
return if current_user.blank?
-
if current_user.is_duo_required?
-
s = Rails.application.secrets
-
@duo_hostname = s.duo_system_admins_api_hostname
-
@sig_request = Duo.sign_request(s.duo_system_admins_integration_key, s.duo_system_admins_secret_key, s.duo_system_admins_application_key, current_user.login)
-
else
-
if Settings.duo_auto_enabled && Settings.duo_custom_enabled
-
if current_user.ssl_account(:default_team).duo_own_used
-
@duo_account = current_user.ssl_account(:default_team).duo_account
-
@duo_hostname = @duo_account.duo_hostname
-
@sig_request = Duo.sign_request(@duo_account ? @duo_account.duo_ikey : "", @duo_account ? @duo_account.duo_skey : "", @duo_account ? @duo_account.duo_akey : "", current_user.login)
-
else
-
s = Rails.application.secrets
-
@duo_hostname = s.duo_api_hostname
-
@sig_request = Duo.sign_request(s.duo_integration_key, s.duo_secret_key, s.duo_application_key, current_user.login)
-
end
-
elsif Settings.duo_auto_enabled && !Settings.duo_custom_enabled
-
s = Rails.application.secrets
-
@duo_hostname = s.duo_api_hostname
-
@sig_request = Duo.sign_request(s.duo_integration_key, s.duo_secret_key, s.duo_application_key, current_user.login)
-
else
-
@duo_account = current_user.ssl_account(:default_team).duo_account
-
@duo_hostname = @duo_account ? @duo_account.duo_hostname : ""
-
@sig_request = Duo.sign_request(@duo_account ? @duo_account.duo_ikey : "", @duo_account ? @duo_account.duo_skey : "", @duo_account ? @duo_account.duo_akey : "", current_user.login)
-
end
-
end
-
end
-
-
def duo_verify
-
if current_user.is_duo_required?
-
s = Rails.application.secrets;
-
@authenticated_user = Duo.verify_response(s.duo_system_admins_integration_key, s.duo_system_admins_secret_key, s.duo_system_admins_application_key, params['sig_response'])
-
else
-
if Settings.duo_auto_enabled && Settings.duo_custom_enabled
-
if current_user.ssl_account(:default_team).duo_own_used
-
@duo_account = current_user.ssl_account(:default_team).duo_account
-
@authenticated_user = Duo.verify_response(@duo_account ? @duo_account.duo_ikey : "", @duo_account ? @duo_account.duo_skey : "", @duo_account ? @duo_account.duo_akey : "", params['sig_response'])
-
else
-
s = Rails.application.secrets;
-
@authenticated_user = Duo.verify_response(s.duo_integration_key, s.duo_secret_key, s.duo_application_key, params['sig_response'])
-
end
-
elsif Settings.duo_auto_enabled && !Settings.duo_custom_enabled
-
s = Rails.application.secrets;
-
@authenticated_user = Duo.verify_response(s.duo_integration_key, s.duo_secret_key, s.duo_application_key, params['sig_response'])
-
else
-
@duo_account = current_user.ssl_account(:default_team).duo_account
-
@authenticated_user = Duo.verify_response(@duo_account ? @duo_account.duo_ikey : "", @duo_account ? @duo_account.duo_skey : "", @duo_account ? @duo_account.duo_akey : "", params['sig_response'])
-
end
-
end if current_user
-
-
if @authenticated_user
-
session[:duo_auth] = true
-
respond_to do |format|
-
format.js {render :json=>url_for_js(current_user)}
-
format.html {redirect_back_or_default account_path(current_user.ssl_account(:default_team) ? current_user.ssl_account(:default_team).to_slug : {})}
-
end
-
else
-
redirect_to action: :new
-
end
-
end
-
-
def destroy
-
if current_user.is_admin?
-
cookies.delete(ResellerTier::TIER_KEY)
-
cookies.delete(ShoppingCart::CART_GUID_KEY)
-
clear_cart
-
end
-
cookies.delete(:acct)
-
current_user_session.destroy
-
Authorization.current_user=nil
-
flash[:notice] = "Successfully logged out."
-
respond_to do |format|
-
format.html {redirect_to new_user_session_url}
-
end
-
end
-
-
private
-
-
def shopping_cart_to_cookie
-
user = @user_session.user
-
set_cookie(:acct, user.ssl_account.acct_number)
-
#we'll know what tier the user is even if s/he is not logged in
-
cookies.delete(ResellerTier::TIER_KEY)
-
-
if user.shopping_cart
-
if cookies[ShoppingCart::CART_KEY].blank?
-
set_cookie(ShoppingCart::CART_KEY, user.shopping_cart.content)
-
else
-
if !cookies[ShoppingCart::CART_GUID_KEY].blank? && cookies[ShoppingCart::CART_GUID_KEY] == user.shopping_cart.guid
-
set_cookie(ShoppingCart::CART_KEY, cookies[ShoppingCart::CART_KEY])
-
else
-
content = user.shopping_cart.content.blank? ? [] : JSON.parse(user.shopping_cart.content)
-
content = shopping_cart_content(content, JSON.parse(cookies[ShoppingCart::CART_KEY]))
-
user.shopping_cart.update_attribute :content, content
-
set_cookie(ShoppingCart::CART_KEY, content)
-
end
-
end
-
end
-
if user.ssl_account.is_registered_reseller?
-
set_cookie(ResellerTier::TIER_KEY, user.ssl_account.reseller.reseller_tier.label)
-
end
-
user
-
end
-
-
def url_for_js(user)
-
redirect = create_ssl_certificate_route(user)
-
@user_session.to_json.chop << ',"redirect_method":"'+redirect[0]+
-
'","url":"'+redirect[1]+'"'+
-
(user.ssl_account.billing_profiles.empty? ? '' :
-
',"billing_profiles":'+render_to_string(partial: '/orders/billing_profiles',
-
locals: {ssl_account: user.ssl_account }).to_json)+'}'
-
end
-
-
def log_failed_attempt(user, params, reason)
-
SystemAudit.create(
-
if user
-
{owner: user,
-
target: nil,
-
action: "Failed login attempt by #{user.login} from ip address #{request.remote_ip}",
-
notes: reason}
-
else
-
{owner: nil,
-
target: nil,
-
action: "Failed login attempt by #{params[:user_session] ? params[:user_session][:login] :
-
params[:login]} from ip address #{request.remote_ip}",
-
notes: reason}
-
end)
-
end
-
-
def shopping_cart_content(content, cart)
-
cart.each_with_index do |i_cart, i|
-
idx = -1
-
-
content.each_with_index do |j_content, j|
-
match = true
-
i_cart.keys.each do |key|
-
if key != ShoppingCart::QUANTITY && key != ShoppingCart::AFFILIATE && i_cart[key] != j_content[key]
-
match = false
-
break
-
end
-
end
-
-
if match
-
idx = j
-
break
-
end
-
end
-
-
if idx == -1
-
if content.kind_of?(Array)
-
content << i_cart
-
else
-
content = [i_cart]
-
end
-
else
-
content[idx][ShoppingCart::QUANTITY] = content[idx][ShoppingCart::QUANTITY].to_i + i_cart[ShoppingCart::QUANTITY].to_i
-
end
-
end
-
-
return content.to_json
-
end
-
end
-
class UsersController < ApplicationController
-
# fix for https://sslcom.airbrake.io/projects/128852/groups/2108774376847787256?resolved=any&tab=overview
-
skip_before_action :require_no_authentication, :only => [:duo_verify]
-
skip_before_action :verify_authenticity_token
-
skip_before_filter :finish_reseller_signup, only: [:cancel_reseller_signup]
-
before_filter :require_no_user, :only => [:new, :create]
-
before_filter :require_user, only: [
-
:show, :edit, :update, :cancel_reseller_signup,
-
:approve_account_invite, :resend_account_invite,
-
:switch_default_ssl_account, :enable_disable, :teams,
-
:index, :admin_show, :search_teams, :archive_team, :retrieve_team
-
]
-
# before_filter :finish_reseller_signup, :only => [:show]
-
before_filter :new_user, :only=>[:create, :new]
-
before_filter :find_ssl_account, only: [:show, :admin_show]
-
before_filter :find_user, :set_admin_flag, :only=>[:edit_email,
-
:edit_password, :update, :login_as, :admin_update, :admin_show,
-
:consolidate, :dup_info, :adjust_funds, :change_login,
-
:switch_default_ssl_account, :index, :admin_activate, :show, :teams]
-
before_filter :set_row_page, only: [:teams]
-
-
# before_filter :index, :only=>:search
-
filter_access_to :all
-
filter_access_to :update, :admin_update, :enable_disable,
-
:switch_default_ssl_account, :decline_account_invite,
-
:approve_account_invite, :create_team, :set_default_team,
-
:index, :edit_email, :edit_password, :leave_team, :dont_show_again, :archive_team, :retrieve_team, attribute_check: true
-
filter_access_to :consolidate, :dup_info, :archive_team, :retrieve_team, :require=>:update
-
filter_access_to :resend_activation, :activation_notice, :require=>:create
-
filter_access_to :edit_password, :edit_email, :cancel_reseller_signup, :teams, :require=>:edit
-
filter_access_to :show_user, :reset_failed_login_count, :require => :ajax
-
-
def new
-
end
-
-
def new_affiliate
-
render action: "new"
-
end
-
-
def search
-
index
-
end
-
-
def search_teams
-
if current_user.is_system_admins?
-
unless params[:search_term].blank?
-
s = params[:search_term]
-
str = s.downcase
-
@found_teams = SslAccount.where(
-
"id = ? OR lower(acct_number) LIKE ? OR lower(company_name) LIKE ? OR lower(ssl_slug) LIKE ?",
-
s, "%#{str}%", "%#{str}%", "%#{str}%"
-
)
-
end
-
json = if @found_teams && @found_teams.any?
-
@order = Order.find_by(reference_number: params[:order]) if params[:order]
-
@certificate_order = CertificateOrder.find_by(ref: params[:certificate_order]) if params[:certificate_order]
-
{content: render_to_string(partial: '/orders/order_transfer_form', layout: false)}
-
else
-
{error: 'Team does not exist.'}
-
end
-
else
-
json = {error: 'Not authorized to do this action!'}
-
end
-
render json: json
-
end
-
-
def index
-
preferred_row_count = current_user.preferred_user_row_count
-
@per_page = params[:per_page] || preferred_row_count.or_else("10")
-
User.per_page = @per_page if User.per_page != @per_page
-
-
if @per_page != preferred_row_count
-
current_user.preferred_user_row_count = @per_page
-
current_user.save(validate: false)
-
end
-
-
# p = {:page => params[:page],per_page: 10}
-
@p = {page: (params[:page] || 1), per_page: @per_page}
-
-
set_users
-
-
if params[:search]
-
search = params[:search].strip.split(" ")
-
role = nil
-
search.delete_if {|s|s =~ /role\:(.+)/; role ||= $1; $1}
-
search = search.join(" ")
-
@users = @users.with_role(role).uniq if role
-
@users = @users.search(search) unless search.blank?
-
end
-
@users = @users.order("created_at desc").paginate(@p)
-
-
respond_to do |format|
-
format.html { render :action => :index }
-
format.xml { render :xml => @users }
-
end
-
end
-
-
def show_user
-
if current_user
-
user = User.unscoped.find(params[:id])
-
render :partial => 'details', :locals => { :user => user }
-
else
-
render :json => 'no-user'
-
end
-
end
-
-
def reset_failed_login_count
-
returnObj = {}
-
-
if current_user
-
user = User.unscoped.find(params[:id])
-
user.update_attribute('failed_login_count', 0)
-
-
returnObj['status'] = 'success'
-
else
-
returnObj['status'] = 'no-user'
-
end
-
-
render :json => returnObj
-
end
-
-
def create
-
reseller = request.subdomain == Reseller::SUBDOMAIN
-
if @user.signup!(params)
-
@user.create_ssl_account
-
if reseller
-
@user.ssl_account.add_role! "new_reseller"
-
@user.ssl_account.set_reseller_default_prefs
-
end
-
@user.set_roles_for_account(
-
@user.ssl_account,
-
[Role.find_by_name((reseller ? Role::RESELLER : Role::OWNER)).id]
-
)
-
-
if Settings.require_signup_password
-
# Check Code Signing Certificate Order for assign as assignee.
-
CertificateOrder.unscoped.search_validated_not_assigned(params[:user][:email]).each do |cert_order|
-
cert_order.update_attribute(:assignee, @user)
-
LockedRecipient.create_for_co(cert_order)
-
end
-
-
# TODO: New Logic for auto activation by signup with password.
-
@user.deliver_auto_activation_confirmation!
-
notice = "Your account has been created."
-
flash[:notice] = notice
-
-
# Auto Login after register
-
@user_session = UserSession.new({
-
login: params[:user][:login],
-
password: params[:user][:password],
-
failed_account: '0'
-
})
-
if @user_session.save
-
user = @user_session.user
-
set_cookie(:acct,user.ssl_account.acct_number)
-
flash[:notice] = "Successfully logged in."
-
redirect_to (account_path(user.ssl_account(:default_team) ?
-
user.ssl_account(:default_team).to_slug :
-
{})) and return
-
end
-
else
-
# TODO: Original Logic for activation by email.
-
@user.deliver_activation_instructions!
-
notice = "Your account has been created. Please check your
-
e-mail at #{@user.email} for your account activation instructions!"
-
flash[:notice] = notice
-
end
-
-
#in production heroku, requests coming FROM a subdomain will not transmit
-
#flash messages to the target page. works fine in dev though
-
redirect_to(request.subdomain == Reseller::SUBDOMAIN ? login_url(:notice => notice) : login_url)
-
else
-
render :action => :new
-
end
-
end
-
-
def show
-
if @user.ssl_account.has_credits? and @user.can_perform_accounting?
-
flash.now[:warning] = "You have unused ssl certificate credits. %s"
-
flash.now[:warning_item] = "Click here to view the list of credits.",
-
credits_certificate_orders_path
-
end
-
if @user.pending_account_invites?
-
render_invite_messages
-
end
-
end
-
-
def cancel_reseller_signup
-
ssl = current_user.ssl_account
-
owner_role = Role.get_owner_id
-
if current_user.role_symbols.include? Role::RESELLER.to_sym
-
ssl.remove_role! 'new_reseller'
-
ssl.reseller.destroy unless (ssl.is_reseller? or ssl.reseller.blank?)
-
current_user.update_account_role(ssl, Role::RESELLER, Role::OWNER)
-
end
-
current_user.set_roles_for_account(ssl, [owner_role]) unless current_user.duplicate_role?(owner_role)
-
flash[:notice] = "reseller signup has been canceled"
-
@user = current_user #for rabl object reference
-
end
-
-
def admin_show
-
@ssl_slug=@ssl_account.to_slug if @ssl_account
-
end
-
-
def edit
-
@user = User.find(params[:id]) if params[:update_own_team_limit] || params[:admin_activate]
-
end
-
-
def login_as
-
end
-
-
def dup_info
-
end
-
-
def adjust_funds
-
amount=params["amount"].to_f*100
-
@user.ssl_account.funded_account.add_cents(amount)
-
SystemAudit.create(owner: current_user, target: @user.ssl_account.funded_account,
-
notes: "amount (in USD): #{amount.to_s}",
-
action: "FundedAccount#add_cents")
-
redirect_to admin_show_user_path(@user)
-
end
-
-
def change_login
-
old = @user.login
-
@user.login = params["login"]
-
if(@user.valid?)
-
User.change_login old, params["login"]
-
SystemAudit.create(owner: current_user, target: @user,
-
notes: "changed login from #{old} to #{params["login"]}",
-
action: "UserController#change_login")
-
else
-
@user.login = old
-
end
-
render action: :admin_show
-
end
-
-
def consolidate
-
login, email = params[:login], params[:email]
-
keep_login = (@user.login == login)
-
keep_email = (@user.email == email)
-
if keep_login && keep_email
-
#delete all duplicate_v2_users
-
elsif email && login && !(keep_login && keep_email)
-
#change both
-
elsif email
-
#change email
-
elsif login
-
#change login
-
end
-
change_password
-
end
-
-
def edit_password
-
@user ||= @current_user
-
permission_denied if !@current_user.is_admin? && (@current_user != @user)
-
@chpwd = !admin_op?
-
end
-
-
def edit_email
-
@user ||= @current_user
-
permission_denied unless admin_or_current_user?
-
end
-
-
def update
-
@user ||= @current_user # makes our views "cleaner" and more consistent
-
edit_email = params[:edit_action] == 'edit_email'
-
unless edit_email
-
@user.changing_password = true #nonelegant hack to trigger validations of password
-
@user.errors[:base]<<(
-
'Old password value does not match password to be changed') unless
-
@user.valid_password?(params[:old_password]) unless admin_op?
-
end
-
old_address=@user.email #be sure to notify where changed from
-
if @user.errors.empty? && @user.update_attributes(params[:user])
-
flash[:notice] = "Account updated."
-
unless edit_email
-
@user.deliver_password_changed!
-
else
-
@user.deliver_email_changed!(old_address)
-
@user.deliver_email_changed!
-
end
-
redirect_to admin_op? ? users_url : edit_account_url
-
elsif edit_email
-
flash[:error] = "Email is not a valid email."
-
redirect_to edit_email_users_path
-
else
-
@chpwd = !admin_op?
-
render :edit_password
-
end
-
end
-
-
def admin_update
-
respond_to do |format|
-
if @user.update_attributes(params[:user])
-
format.js { render :json=>@user.to_json}
-
else
-
format.js { render :json=>@user.errors.to_json}
-
end
-
end
-
end
-
-
def resend_activation
-
if params[:login]
-
@user = User.find_by_login params[:login]
-
if @user
-
if !@user.active?
-
@user.deliver_activation_instructions!
-
flash[:notice] = "Account activation instructions are on it's way - please check your e-mail for further instructions"
-
else
-
flash[:notice] = "Looks like user #{params[:login]} has already been activated"
-
end
-
else
-
if DuplicateV2User.find_by_login params[:login]
-
flash[:notice] = "Ooops, looks like user #{params[:login]} has been consolidated with another account.
-
Please contact support@ssl.com for more details"
-
else
-
flash[:notice] = "Ooops, looks like user #{params[:login]} doesn't exist in our system"
-
end
-
end
-
redirect_to login_path
-
else
-
redirect_to activation_notice_users_path
-
end
-
end
-
-
def switch_default_ssl_account
-
old_ssl_slug = @ssl_slug
-
@switch_ssl_account = params[:ssl_account_id]
-
session[:switch_ssl_account] = @switch_ssl_account
-
session[:old_ssl_slug] = old_ssl_slug
-
team = SslAccount.find(params[:ssl_account_id])
-
if team.duo_enabled
-
redirect_to duo_user_path(@user.id, ssl_slug: @ssl_slug)
-
else
-
if @switch_ssl_account && @user.get_all_approved_accounts.map(&:id).include?(@switch_ssl_account.to_i)
-
@ssl_slug = SslAccount.find(@switch_ssl_account).to_slug
-
@user.set_default_ssl_account(@switch_ssl_account)
-
flash[:notice] = "You have switched to team %s."
-
flash[:notice_item] = "<strong>#{SslAccount.find(@user.default_ssl_account).get_team_name}</strong>"
-
else
-
flash[:error] = "Something went wrong. Please try again!"
-
end
-
redirect_to redirect_back_w_team_slug(old_ssl_slug)
-
end
-
end
-
-
def duo
-
team = SslAccount.find(session[:switch_ssl_account])
-
if team.duo_own_used
-
@duo_account = team.duo_account
-
@duo_hostname = @duo_account.duo_hostname
-
@sig_request = Duo.sign_request(@duo_account ? @duo_account.duo_ikey : "", @duo_account ? @duo_account.duo_skey : "", @duo_account ? @duo_account.duo_akey : "", current_user.login)
-
else
-
s = Rails.application.secrets;
-
@duo_hostname = s.duo_api_hostname
-
@sig_request = Duo.sign_request(s.duo_integration_key, s.duo_secret_key, s.duo_application_key, current_user.login)
-
end
-
end
-
-
def duo_verify
-
old_ssl_slug = session[:old_ssl_slug]
-
@switch_ssl_account = session[:switch_ssl_account]
-
@user = current_user
-
team = SslAccount.find(session[:switch_ssl_account])
-
if team.duo_own_used
-
@duo_account = team.duo_account
-
@authenticated_user = Duo.verify_response(@duo_account ? @duo_account.duo_ikey : "", @duo_account ? @duo_account.duo_skey : "", @duo_account ? @duo_account.duo_akey : "", params['sig_response'])
-
else
-
s = Rails.application.secrets;
-
@authenticated_user = Duo.verify_response(s.duo_integration_key, s.duo_secret_key, s.duo_application_key, params['sig_response'])
-
end
-
if @authenticated_user
-
if @switch_ssl_account && @user.get_all_approved_accounts.map(&:id).include?(@switch_ssl_account.to_i)
-
@user.set_default_ssl_account(@switch_ssl_account)
-
flash[:notice] = "You have switched to team %s."
-
flash[:notice_item] = "<strong>#{@user.ssl_account.get_team_name}</strong>"
-
set_ssl_slug(@user)
-
else
-
flash[:error] = "Something went wrong. Please try again!"
-
end
-
redirect_to account_path(ssl_slug: @ssl_slug)
-
else
-
redirect_to redirect_back_w_team_slug(old_ssl_slug)
-
end
-
end
-
-
def approve_account_invite
-
user = User.find params[:id]
-
errors = user.approve_invite(params)
-
if errors.any?
-
flash[:error] = "Unable to approve due to errors. #{errors.join(' ')}."
-
else
-
team = SslAccount.find(params[:ssl_account_id])
-
flash[:notice] = "You have accepted the invitation to <strong>#{team.get_team_name}</strong>.<br />
-
Would you like to set <strong>#{team.get_team_name}</strong> as your Default Team?
-
<i>(This setting may be changed later.)</i><br />
-
%s <span class='chip medium--grey'>NO</span><br /><br />
-
The current default is <strong>#{user.ssl_account.get_team_name}</strong>."
-
flash[:notice_item] = view_context.link_to("<span class='chip medium'>YES</span>".html_safe,
-
switch_default_ssl_account_user_path(ssl_account_id: params[:ssl_account_id]))
-
end
-
params[:to_teams] ? redirect_to(teams_user_path(user)) : redirect_to(account_path(ssl_slug: @ssl_slug))
-
end
-
-
def decline_account_invite
-
user = User.find params[:id]
-
if user.user_declined_invite?(params)
-
flash[:error] = 'You have already declined this invite.'
-
else
-
ssl = SslAccount.find(params[:ssl_account_id])
-
if ssl
-
user.decline_invite(params)
-
flash[:notice] = "You have successfully declined a recent account invite to team #{ssl.get_team_name}."
-
end
-
end
-
params[:to_teams] ? redirect_to(teams_user_path(user)) : redirect_to(account_path(ssl_slug: @ssl_slug))
-
end
-
-
def resend_account_invite
-
user = User.find params[:id]
-
errors = user.resend_invitation_with_token(params)
-
if errors.any?
-
flash[:error] = "Unable to send invitation due to errors. #{errors.join(' ')}"
-
else
-
flash[:notice] = 'You successfully renewed the invitation token and sent notification to the user.'
-
end
-
redirect_to users_path(ssl_slug: @ssl_slug)
-
end
-
-
def enable_disable
-
update_user_status(params) if params[:user][:status]
-
respond_to do |format|
-
format.js {render json: @user.to_json}
-
end
-
end
-
-
def enable_disable_duo
-
update_user_duo_status(params) if params[:user][:duo_enabled]
-
respond_to do |format|
-
format.js {render json: @user.to_json}
-
end
-
end
-
-
def teams
-
# p = {page: params[:page]}
-
team = params[:team]
-
# @teams = @user.get_all_approved_accounts
-
@teams = @user.get_all_approved_teams
-
unless team.blank?
-
team = team.strip.downcase
-
# @teams = @teams.where("acct_number = ? OR ssl_slug = ? OR company_name = ?", team, team, team)
-
@teams = @teams.search_team(team)
-
end
-
@teams = @teams.paginate(@p)
-
end
-
-
def archive_team
-
team = (current_user.is_system_admins? ? SslAccount.unscoped : current_user.ssl_accounts).find(params[:ssl_account_id])
-
team.archive! if team.active?
-
-
flash[:notice] = 'Your team "#' + team.to_slug + '" has been archived. You can retrieve later again.'
-
redirect_to teams_user_path(current_user)
-
end
-
-
def retrieve_team
-
team = SslAccount.unscoped.find(params[:ssl_account_id])
-
team.retrieve! if team.archived?
-
-
flash[:notice] = 'Your team "#' + team.to_slug + '" has been retrieved.'
-
redirect_to teams_user_path(current_user)
-
end
-
-
def create_team
-
@user = User.find params[:id]
-
if @user && !@user.max_teams_reached? && params[:create] && params[:team_name]
-
@new_team = create_custom_ssl_acct(@user, params)
-
if @new_team.persisted?
-
flash[:notice] = "Team #{@new_team.company_name} has been successfully created."
-
autoadd_users_to_team
-
redirect_to teams_user_path
-
else
-
flash[:error] = 'Failed to create new team, please try again.'
-
redirect_to :back
-
end
-
end
-
end
-
-
def autoadd_users_to_team
-
if params[:auto_add_user_ids] && params[:auto_add_user_ids].any?
-
users = User.where(id: params[:auto_add_user_ids].map(&:to_i))
-
users.each do |user|
-
user.ssl_accounts << @new_team
-
-
# add roles from most recent team (shared w/current_user) they were added to
-
roles = current_user.get_auto_add_user_roles(user)
-
roles = [Role.get_individual_certificate_id] if roles.empty?
-
user.set_roles_for_account(@new_team, roles)
-
-
# send invitation email
-
current_user.invite_existing_user(
-
user: {email: user.email, ssl_account_id: @new_team.id},
-
from_user: current_user
-
)
-
-
SystemAudit.create(
-
owner: current_user,
-
target: user,
-
action: 'Invite user to team (Users#create_team)',
-
notes: "Ssl.com user #{user.login} was invited to team #{@new_team.get_team_name} by #{current_user.login}."
-
)
-
end
-
end
-
end
-
-
def set_default_team
-
@user = User.find params[:id]
-
if @user && params[:ssl_account_id]
-
ssl = SslAccount.find(params[:ssl_account_id])
-
if ssl && @user.set_default_team(ssl)
-
flash[:notice] = "Team #{ssl.get_team_name} has been set as default team."
-
else
-
flash[:error] = 'Something went wrong, please try again.'
-
end
-
end
-
redirect_to teams_user_path
-
end
-
-
def set_default_team_max
-
@user = User.find params[:id]
-
max = params[:user][:max_teams]
-
if @user && max
-
@user.update(max_teams: max)
-
flash[:notice] = "User #{@user.login} team limit has been successfully updated to #{max}."
-
end
-
redirect_to users_path
-
end
-
-
def leave_team
-
@user = User.find params[:id]
-
team = @user.ssl_accounts.find(params[:ssl_account_id]) if params[:ssl_account_id]
-
own_team = (team.get_account_owner == @user) if team
-
if team && !own_team
-
@user.leave_team(team)
-
flash[:notice] = "You have successfully left team #{team.get_team_name}."
-
else
-
flash[:error] = own_team ? "You cannot leave team that you own!" : "Something went wrong, please try again."
-
end
-
redirect_to teams_user_path
-
end
-
-
def dont_show_again
-
@user = User.find params[:id]
-
@user.update(persist_notice: false)
-
respond_to {|format| format.js {render json: 'ok'}}
-
end
-
-
def admin_activate
-
@user = User.find params[:id]
-
@user.activate!(params)
-
if @user.valid?
-
@user.approve_all_accounts(:log_invite)
-
-
# Send activation email to user by system admin
-
@user.deliver_activation_confirmation_by_sysadmin!(params[:user][:password])
-
-
flash[:notice] = "User #{@user.login} has been successfully activated and sent email to " + params[:user][:login]
-
redirect_to users_path
-
else
-
flash[:error] = "Unable to activate user due to errors. #{@user.errors.full_messages.join(', ')}"
-
redirect_to edit_user_path(@user, admin_activate: true)
-
end
-
end
-
-
private
-
-
def set_row_page
-
preferred_row_count = current_user.preferred_team_row_count
-
@per_page = params[:per_page] || preferred_row_count.or_else("10")
-
SslAccount.per_page = @per_page if SslAccount.per_page != @per_page
-
-
if @per_page != preferred_row_count
-
current_user.preferred_team_row_count = @per_page
-
current_user.save(validate: false)
-
end
-
-
@p = {page: (params[:page] || 1), per_page: @per_page}
-
end
-
-
def new_user
-
@user = User.new
-
end
-
-
def find_user
-
@user=if current_user.is_system_admins?
-
if params[:id]
-
User.unscoped.find(params[:id])
-
elsif @ssl_account
-
@ssl_account.get_account_owner
-
else
-
current_user
-
end
-
else
-
current_user
-
end
-
end
-
-
def admin_op?
-
(@user!=@current_user &&
-
(@current_user.is_admin? || @current_user.is_owner?)
-
) unless @current_user.blank?
-
end
-
-
def set_admin_flag
-
@user.admin_update=true if admin_op?
-
end
-
-
def set_users
-
if current_user.is_system_admins?
-
@users = @ssl_account.try(:users) || User.unscoped
-
else
-
@users = current_user.manageable_users
-
end
-
end
-
-
def admin_or_current_user?
-
@current_user.is_admin? || @current_user == @user
-
end
-
-
def render_invite_messages
-
invites = current_user.get_pending_accounts
-
if invites.any?
-
invites.each do |invite|
-
new_params = {ssl_account_id: invite[:ssl_account_id], token: invite[:approval_token]}
-
accept_link = view_context.link_to('here',
-
approve_account_invite_user_path(current_user, new_params))
-
decline_link = view_context.link_to('decline',
-
decline_account_invite_user_path(current_user, new_params))
-
flash[:notice] = "You have been invited to join account ##{invite[:acct_number]}.
-
Please click #{accept_link} to accept the invitation. Click %s to reject."
-
flash[:notice_item] = decline_link
-
end
-
end
-
end
-
end
-
-
def update_user_status(params)
-
target_user = User.unscoped.find params[:id]
-
target_status = params[:user][:status].to_sym
-
if target_user && target_status
-
target_user.set_status_all_accounts(target_status) if current_user.is_system_admins?
-
unless (current_user.roles_for_account & Role.can_manage_users).empty?
-
target_user.set_status_for_account(target_status, current_user.ssl_account)
-
end
-
end
-
end
-
-
def update_user_duo_status(params)
-
target_user = User.unscoped.find params[:id]
-
target_status = params[:user][:duo_enabled].to_sym
-
target_user.update_attribute(:duo_enabled, target_status)
-
end
-
-
def create_custom_ssl_acct(user, params)
-
slug_valid = params[:ssl_slug] && SslAccount.ssl_slug_valid?(params[:ssl_slug])
-
user.create_ssl_account(
-
[Role.get_owner_id],
-
{company_name: params[:team_name], ssl_slug: (slug_valid ? params[:ssl_slug] : nil)}
-
)
-
end
-
-
def redirect_back_w_team_slug(replace_slug)
-
req = request.env['HTTP_REFERER']
-
req.present? ? req.gsub(replace_slug, @ssl_slug) : account_path(ssl_slug: @ssl_slug)
-
end
-
class ValidationHistoriesController < ApplicationController
-
before_filter :find_validation_history, :only=>[:update]
-
filter_access_to :documents, :require=>:read
-
-
def update
-
respond_to do |format|
-
if @validation_history.update_attributes(params[:validation_history])
-
#protected for admins only
-
if current_user.is_admin?
-
@validation_history.update_attribute(:publish_to_site_seal_approval,
-
params[:validation_history][:publish_to_site_seal_approval]) if
-
params[:validation_history][:publish_to_site_seal_approval]
-
r = params[:validation_history][:validation_rules]
-
unless r.blank?
-
if r.include?(Validation::NONE_SELECTED)
-
@validation_history.validation_rules.delete_all
-
else
-
r.each do |i|
-
vr = ValidationRule.find(i)
-
@validation_history.validation_rules << vr unless vr.blank? ||
-
@validation_history.validation_rules.include?(vr)
-
end
-
end
-
end
-
m = params[:validation_history][:satisfies_validation_methods]
-
unless m.blank?
-
m = nil if m.include?(Validation::NONE_SELECTED)
-
@validation_history.
-
update_attribute :satisfies_validation_methods, m
-
end
-
end
-
format.js { render :json=>@validation_history.to_json}
-
else
-
format.js { render :json=>@validation_history.errors.to_json}
-
end
-
end
-
end
-
-
def index
-
@validation_histories=(current_user.is_system_admins? ? ValidationHistory : current_user.validation_histories).all
-
respond_to do |format|
-
format.html { render :action => :index }
-
end
-
end
-
-
def documents
-
vh = if params[:registrant]
-
r = Registrant.find_by(id: params[:registrant])
-
r.validation_histories.find_by(id: params[:id])
-
else
-
(current_user.is_system_admins? ? ValidationHistory : current_user.validation_histories).find(params[:id])
-
end
-
if vh
-
# => Use this if we want to store to the file system instead of s3.
-
# Comment out the redirecto_to
-
# send_file vh.document.path(params['style'].to_sym),
-
# :type => vh.document.content_type, :disposition => 'attachment'
-
if vh.document_file_name.force_encoding('UTF-8').include? (params['style']+'.'+params['extension']) #files with multiple .'s present a problem'
-
style = vh.document.default_style
-
else
-
style = params['style'].to_sym
-
end
-
redirect_to vh.authenticated_s3_get_url :style=> style
-
else
-
render :status=>403
-
end
-
end
-
-
private
-
-
def find_validation_history
-
if params[:id]
-
@validation_history=ValidationHistory.find(params[:id])
-
end
-
end
-
end
-
class ValidationRulingsController < ApplicationController
-
end
-
open3 = "open3"
-
open3.insert(0,'win32/') if RUBY_PLATFORM =~ /mswin32/
-
require open3
-
require 'zip/zipfilesystem'
-
require 'tempfile'
-
include Open3
-
-
class ValidationsController < ApplicationController
-
before_filter :require_user, only: [:index, :new, :edit, :show, :upload, :document_upload, :get_asynch_domains,
-
:cancel_validation_process]
-
before_filter :find_validation, only: [:update, :new]
-
before_filter :find_certificate_order, only: [:new, :edit, :show, :upload, :document_upload, :request_approve_phone_number]
-
before_filter :set_supported_languages, only: [:verification]
-
before_filter :set_row_page, only: [:index, :search]
-
-
filter_access_to :all
-
filter_access_to [:upload, :document_upload, :verification, :email_verification_check, :automated_call,
-
:phone_verification_check, :register_callback], :require=>:update
-
filter_access_to :requirements, :send_dcv_email, :domain_control, :ev, :organization, require: :read
-
filter_access_to :update, :new, :attribute_check=>true
-
filter_access_to :edit, :show, :attribute_check=>true
-
filter_access_to :admin_manage, :attribute_check=>true
-
filter_access_to :send_to_ca, require: :sysadmin_manage
-
filter_access_to :get_asynch_domains, :remove_domains, :get_email_addresses, :send_callback,
-
:add_super_user_email, :request_approve_phone_number, :cancel_validation_process, :require=>:ajax
-
in_place_edit_for :validation_history, :notes
-
-
def search
-
index
-
end
-
-
def new
-
url = nil
-
cc = @certificate_order.certificate_content
-
-
if !@certificate_order.certificate.is_server?
-
url = document_upload_certificate_order_validation_url(certificate_order_id: @certificate_order.ref)
-
else
-
if cc.issued?
-
checkout = {checkout: "true"}
-
if cc.signed_certificate
-
flash.now[:notice] = "SSL certificate has been issued"
-
elsif @certificate_order.all_domains_validated?
-
flash.now[:notice] = "All domains have been validated, please wait for certificate issuance"
-
end
-
-
respond_to do |format|
-
format.html { redirect_to certificate_order_path({id: @certificate_order.ref}.merge!(checkout))}
-
end
-
else
-
if cc.contacts_provided? or cc.info_provided?
-
cc.pend_validation!(host: request.host_with_port)
-
end
-
-
# @all_validated = true
-
@validated_domains = ''
-
@caa_check_domains = ''
-
validated_domain_arry = []
-
caa_check_domain_arry = []
-
public_key_sha1 = Settings.compare_public_key ? cc.cached_csr_public_key_sha1 : nil
-
unless cc.ca.blank?
-
cnames = cc.certificate_names.includes(:validated_domain_control_validations)
-
team_cnames = @certificate_order.ssl_account.all_certificate_names(cnames.pluck(:name),"validated").
-
includes(:validated_domain_control_validations)
-
-
# Team level validation check
-
@ds = {}
-
cnames.each do |cn|
-
team_level_validated = false
-
-
team_cnames.each do |team_cn|
-
if team_cn.name == cn.name
-
team_dcv = team_cn.validated_domain_control_validations.last
-
-
if team_dcv && (Settings.compare_public_key ? team_dcv.validated?(nil,public_key_sha1) : true)
-
team_level_validated = true
-
-
@ds[team_cn.name] = {}
-
@ds[team_cn.name]['method'] = team_dcv.dcv_method
-
@ds[team_cn.name]['attempted_on'] = team_dcv.created_at
-
if team_cn.caa_passed
-
@ds[team_cn.name]['caa_check'] = 'passed'
-
else
-
@ds[team_cn.name]['caa_check'] = 'failed'
-
caa_check_domain_arry << team_cn.name
-
end
-
end
-
-
break if team_level_validated
-
end
-
end
-
-
(validated_domain_arry << cn.name) if cn.validated_domain_control_validations.last
-
end
-
-
@all_validated=@certificate_order.domains_validated?
-
if @all_validated and cc.signed_certificate.blank? and !cc.issued?
-
cc.validate! if cc.pending_validation?
-
api_log_entry=@certificate_order.apply_for_certificate(
-
mapping: @certificate_order.certificate_content.ca,
-
current_user: current_user)
-
if api_log_entry and api_log_entry.instance_of?(SslcomCaRequest) and api_log_entry.response=~/Check CAA/
-
flash[:error] =
-
"CAA validation failed. See https://#{Settings.portal_domain}/how-to/configure-caa-records-to-authorize-ssl-com/"
-
end
-
end
-
-
@validated_domains = validated_domain_arry.join(',')
-
@caa_check_domains = caa_check_domain_arry.join(',')
-
else
-
mdc_validation = ComodoApi.mdc_status(@certificate_order)
-
@ds = mdc_validation.domain_status
-
-
if @ds
-
# tmpCnt = 0
-
# before = DateTime.now
-
names=cc.certificate_names.find_by_domains(@ds.keys)
-
@ds.each do |key, value|
-
if value['status'].casecmp('validated') != 0
-
@all_validated = false if @all_validated
-
else
-
validated_domain_arry << key
-
ext_order_number = @certificate_order.external_order_number || 'eon'
-
cache = nil # Rails.cache.read(params[:certificate_order_id] + ':' + ext_order_number + ':' + key)
-
-
if cache.blank?
-
cn = names.find_by_name(key)
-
dcv = cn.blank? ? nil : cn.domain_control_validations.last
-
value['attempted_on'] = dcv.blank? ? 'n/a' : dcv.created_at
-
-
if Settings.enable_caa && cn.try(:caa_passed)
-
value['caa_check'] = 'passed'
-
else
-
value['caa_check'] = 'failed'
-
caa_check_domain_arry << key
-
end
-
-
# Rails.cache.write(params[:certificate_order_id] + ':' + ext_order_number + ':' + key, value['attempted_on'])
-
else
-
value['attempted_on'] = cache
-
end
-
end
-
end
-
# after = DateTime.now
-
# subtract = after.to_i - before.to_i
-
-
@validated_domains = validated_domain_arry.join(',')
-
@caa_check_domains = caa_check_domain_arry.join(',')
-
-
# if all_validated
-
# url=certificate_order_path(@ssl_slug, @certificate_order)
-
# end
-
else
-
@all_validated = false
-
# flash[:error] = "Currently Comodoca API is under working, please try again after some minutes."
-
end
-
end
-
end
-
end
-
redirect_to url and return unless url.blank?
-
end
-
-
def dcv_validate
-
@certificate_order = CertificateOrder.find_by_ref(params['certificate_order_id'])
-
cc = @certificate_order.certificate_content
-
if(params['authenticity_token'])
-
identifier = params['validate_code']
-
cnames = cc.certificate_names
-
all_validated = true
-
cnames.includes(:domain_control_validations).each do |cn|
-
dcv = cn.domain_control_validations.last
-
if dcv.identifier == identifier
-
dcv.update_attribute(:identifier_found, true)
-
end
-
all_validated = false unless dcv.identifier_found
-
end
-
if all_validated
-
cc.validate! unless cc.validated?
-
@certificate_order.apply_for_certificate(mapping:
-
@certificate_order.certificate.cas.ssl_account_or_general_default(current_user.ssl_account).last) unless @certificate_order.certificate_content.ca.blank?
-
end
-
end
-
end
-
-
def remove_domains
-
result_obj = {}
-
-
if current_user
-
domain_name_arry = params['domain_names'].split(',')
-
# order_number = CertificateOrder.find_by_ref(params['certificate_order_id']).external_order_number
-
certificate_order = current_user.certificate_order_by_ref(params[:certificate_order_id])
-
certificate_content = certificate_order.certificate_content
-
certificate_names = certificate_content.certificate_names
-
-
unless certificate_content.ca_id.nil?
-
domains = certificate_content.domains
-
domains_from_cert_names = certificate_names.pluck(:name)
-
-
if domains.size == domains_from_cert_names.size && (domains & domains_from_cert_names).size == domains.size
-
remain_domains = domains - domain_name_arry
-
else
-
remain_domains = domains_from_cert_names - domain_name_arry
-
end
-
-
certificate_content.update_column :domains, remain_domains
-
end
-
-
certificate_names.where{ name >> domain_name_arry }.each do |cn_obj|
-
if certificate_content.ca_id.nil?
-
res = ComodoApi.auto_remove_domain(domain_name: cn_obj, order_number: certificate_order.external_order_number)
-
-
error_code = -1
-
error_message = ''
-
-
if res.index('errorCode') && res.index('errorMessage')
-
error_code = res.split('&')[0].split('=')[1].to_i
-
error_message = res.split('&')[1].split('=')[1]
-
elsif res.index('errorCode') && !res.index('errorMessage')
-
error_code = 0
-
else
-
error_message = res
-
end
-
-
if error_code.zero?
-
# Remove Domain from Notification Group
-
NotificationGroup.auto_manage_cert_name(certificate_content, 'delete', cn_obj)
-
-
# Remove Domain Object
-
dcvs = cn_obj.domain_control_validations
-
if dcvs.size > 0
-
dcvs.delete_all
-
end
-
cn_obj.destroy
-
-
# TODO: Remove cache for removed domain
-
# Rails.cache.delete(params[:certificate_order_id] + ':' + domain_name)
-
Rails.cache.delete(params[:certificate_order_id] + ':' + cn_obj.name)
-
else
-
result_obj[cn_obj.name] = error_message.gsub("+", " ").gsub("%27", "'").gsub("%21", "!")
-
end
-
else
-
dcvs = cn_obj.domain_control_validations
-
if dcvs.size > 0
-
dcvs.delete_all
-
end
-
# Remove Domain from Notification Group
-
NotificationGroup.auto_manage_cert_name(certificate_content, 'delete', cn_obj)
-
-
# Remove Domain Object
-
cn_obj.destroy
-
-
# TODO: Remove cache for removed domain
-
Rails.cache.delete(params[:certificate_order_id] + ':' + cn_obj.name)
-
end
-
end
-
else
-
result_obj['no-user'] = "true"
-
end
-
-
render :json => result_obj
-
end
-
-
def get_email_addresses
-
returnObj = {}
-
if current_user
-
addresses = CertificateName.candidate_email_addresses(params['domain_name'])
-
addresses.delete("none")
-
-
returnObj['caa_check'] = ''
-
returnObj['new_emails'] = {}
-
-
addresses.each do |addr|
-
returnObj['new_emails'][addr] = addr
-
end
-
else
-
returnObj['no-user'] = "true"
-
end
-
-
render :json => returnObj
-
end
-
-
def add_super_user_email
-
returnObj = {}
-
-
if current_user
-
params['domain_emails'].each do |domain_email|
-
CertificateName.add_email_address_candidate(domain_email.split('|')[0], domain_email.split('|')[1])
-
end
-
-
returnObj['status'] = "true"
-
else
-
returnObj['no-user'] = "true"
-
end
-
-
render :json => returnObj
-
end
-
-
def get_asynch_domains
-
co = (current_user.is_system_admins? ? CertificateOrder :
-
current_user.certificate_orders).find_by_ref(params[:certificate_order_id])
-
cn = co.certificate_content.certificate_names.find_by_name(params['domain_name']) if co
-
-
returnObj = Rails.cache.fetch(cn.get_asynch_cache_label) do
-
if cn
-
ds = params['domain_status']
-
-
if co.certificate_content.ca
-
dcv = cn.validated_domain_control_validations.last
-
domain_status =
-
if dcv
-
"validated"
-
else
-
co.ssl_account.other_dcvs_satisfy_domain(cn)
-
dcv = cn.validated_domain_control_validations.last
-
if dcv
-
"validated"
-
else
-
dcv = cn.domain_control_validations.last
-
"pending"
-
end
-
end
-
if dcv
-
domain_method = dcv.email_address ? dcv.email_address : dcv.dcv_method
-
else
-
domain_status = !ds.blank? && ds['status'] ? ds['status'] : nil
-
domain_method = !ds.blank? && ds['method'] ? ds['method'] : nil
-
end
-
else
-
domain_status = !ds.blank? && ds['status'] ? ds['status'] : nil
-
domain_method = !ds.blank? && ds['method'] ? ds['method'] : nil
-
end
-
-
addresses =
-
if co.certificate_content.ca.blank? and co.external_order_number
-
ComodoApi.domain_control_email_choices(cn.name).email_address_choices
-
else
-
CertificateName.candidate_email_addresses(cn.non_wildcard_name)
-
end
-
addresses.delete("none")
-
-
optionsObj = {}
-
viaEmail = {}
-
viaCSR = {}
-
-
if dcv or !ds.blank?
-
addresses.each do |addr|
-
viaEmail[addr] = addr
-
end
-
-
viaCSR['http_csr_hash'] = 'CSR hash text file using http://'
-
viaCSR['https_csr_hash'] = 'CSR hash text file using https://'
-
viaCSR['cname_csr_hash'] = 'Add cname entry'
-
-
optionsObj['Validation via email'] = viaEmail
-
optionsObj['Validation via csr hash'] = viaCSR
-
-
{
-
'tr_info' => {
-
'options' => optionsObj,
-
'slt_option' => domain_method ?
-
domain_method.downcase.gsub('pre-validated %28', '').gsub('%29', '').gsub(' ', '_') : nil,
-
'pretest' => 'n/a',
-
'attempt' => domain_method ? domain_method.downcase.gsub('%28', ' ').gsub('%29', ' ') : '',
-
'attempted_on' => dcv.blank? ? 'n/a' : dcv.created_at.strftime('%Y-%m-%d %H:%M:%S'),
-
'status' => domain_status ? domain_status.downcase : '',
-
'caa_check' => ''
-
},
-
'tr_instruction' => false
-
}
-
else
-
optionsObj = {}
-
addresses ||= CertificateName.candidate_email_addresses(cn.non_wildcard_name)
-
-
viaEmail = {}
-
viaCSR = {}
-
-
addresses.each do |addr|
-
viaEmail[addr] = addr
-
end
-
-
viaCSR['http_csr_hash'] = 'CSR hash text file using http://'
-
viaCSR['https_csr_hash'] = 'CSR hash text file using https://'
-
viaCSR['cname_csr_hash'] = 'Add cname entry'
-
-
optionsObj['Validation via email'] = viaEmail
-
optionsObj['Validation via csr hash'] = viaCSR
-
-
le = cn.domain_control_validations.last_emailed
-
-
{
-
'tr_info' => {
-
'options' => optionsObj,
-
'slt_option' => le.blank? ? nil : le.email_address,
-
'pretest' => 'n/a',
-
'attempt' => 'validation not performed yet',
-
'attempted_on' => 'n/a',
-
'status' => 'waiting',
-
'caa_check' => ''
-
},
-
'tr_instruction' => false
-
}
-
end
-
end
-
end
-
-
render :json => returnObj
-
end
-
-
def index
-
# p = {:page => params[:page]}
-
@certificate_orders =
-
if !params[:search].blank? && (@search = params[:search])
-
current_user.is_admin? ?
-
(@ssl_account.try(:certificate_orders) || CertificateOrder)
-
.not_test.search_with_csr(params[:search]).unvalidated.not_csr_blank :
-
current_user.ssl_account.certificate_orders.not_test.search(params[:search]).unvalidated.not_csr_blank
-
else
-
current_user.is_admin? ?
-
(@ssl_account.try(:certificate_orders) || CertificateOrder).unvalidated.not_csr_blank :
-
current_user.ssl_account.certificate_orders.unvalidated.not_csr_blank
-
end
-
-
@certificate_orders = @certificate_orders.paginate(@p)
-
-
respond_to do |format|
-
format.html { render :action => :index }
-
format.xml { render :xml => @certificate_orders }
-
end
-
end
-
-
def show_document_file
-
release = Release.find(params[:id])
-
if current_user.try(:can_view_release?, Release.find(params[:id]))
-
content = release.content
-
send_file content.private_full_filename
-
send_file @appraisal.doc.path, :type => @appraisal.doc_content_type, :disposition => 'attachment'
-
else
-
render :status=>403
-
end
-
end
-
-
def send_dcv_email
-
if params[:domain_control_validation_email] && params[:domain_control_validation_id]
-
@dcv = DomainControlValidation.find(params[:domain_control_validation_id])
-
@dcv.send_to params[:domain_control_validation_email]
-
end
-
respond_to do |format|
-
format.js {render json: (@dcv.errors.blank? ? @dcv : @dcv.errors).to_json, status: :ok}
-
end
-
end
-
-
def upload_for_registrant
-
@i = 0
-
@error = []
-
@files = params[:filedata] || []
-
-
if params[:filedata]
-
upload_documents(params[:filedata], :saved_registrant_documents)
-
end
-
-
if @error.blank?
-
if @files.blank?
-
flash[:error] = "Documents were not saved, please upload at least one file."
-
else
-
files_were = (@i > 1 || @i==0) ? "documents were" : "document was"
-
flash[:notice] = "#{@i.in_words.capitalize} (#{@i}) #{files_were} successfully saved."
-
end
-
else
-
flash[:error] = "Failed to upload documents due to errors: #{@error.join(', ')}"
-
end
-
redirect_to contact_path(@ssl_slug, @registrant.id, saved_contact: true)
-
end
-
-
#user can select to upload documents or do dcv (email or http) or do both
-
def upload
-
@i = 0
-
@error = []
-
@files = params[:filedata] || []
-
@files += params[:iv_filedata] if params[:iv_filedata]
-
@files += params[:ov_filedata] if params[:ov_filedata]
-
-
unless params[:refer_to_others].blank? || params[:refer_to_others]=="false"
-
attrs=%w(email_addresses other_party_requestable_type other_party_requestable_id preferred_sections preferred_show_order_number)
-
@other_party_validation_request =
-
OtherPartyValidationRequest.new(Hash[*attrs.map{|a|[a.to_sym,params[a.to_sym]] if params[a.to_sym]}.
-
compact.flatten])
-
current_user.other_party_requests << @other_party_validation_request
-
unless @other_party_validation_request.valid?
-
@error<<@other_party_validation_request.errors.full_messages
-
flash[:opvr_error]=true
-
end
-
flash[:opvr]=true
-
flash[:email_addresses]=params[:email_addresses]
-
end
-
-
upload_documents(@files, :validation) if params[:filedata]
-
upload_documents(params[:iv_filedata], :iv_documents) if params[:iv_filedata]
-
upload_documents(params[:ov_filedata], :ov_documents) if params[:ov_filedata]
-
-
respond_to do |format|
-
if @error.blank? && (@other_party_validation_request.blank? ? true : @other_party_validation_request.valid?)
-
unless @files.blank?
-
files_were = (@i > 1 or @i==0)? "documents were" : "document was"
-
flash[:notice] = "#{@i.in_words.capitalize} (#{@i}) #{files_were}
-
successfully saved."
-
@certificate_order.confirmation_recipients.map{|r|r.split(" ")}.flatten.uniq.each do |c|
-
OrderNotifier.validation_documents_uploaded(c, @certificate_order, @files).deliver
-
end
-
OrderNotifier.validation_documents_uploaded(Settings.notify_address, @certificate_order, @files).deliver
-
OrderNotifier.validation_documents_uploaded_comodo("evdocs@comodo.com", @certificate_order, @files).
-
deliver if (@certificate_order.certificate.is_ev? && @certificate_order.ca_name=="comodo")
-
end
-
checkout={}
-
if @certificate_order.certificate_content.contacts_provided?
-
@certificate_order.certificate_content.pend_validation!(host: request.host_with_port) if @other_party_validation_request.blank?
-
checkout={checkout: "true"}
-
end
-
@validation_histories = @certificate_order.validation_histories
-
format.html { redirect_to certificate_order_path({id: @certificate_order.ref}.merge!(checkout))}
-
format.xml { render :xml => @release,
-
:status => :created,
-
:location => @release }
-
else
-
(flash[:error] = @error.is_a?(Array) ? @error.join(", ") : @error) unless @error.blank?
-
format.html { redirect_to new_certificate_order_validation_path(
-
@certificate_order) }
-
format.xml { render :xml => @release.errors,
-
:status => :unprocessable_entity }
-
end
-
end
-
end
-
-
def update
-
respond_to do |format|
-
#protected for admins only
-
if current_user.is_admin?
-
@co = CertificateOrder.find params[:certificate_order]
-
cc = @co.certificate_content
-
vrs = @validation.validation_rulings
-
vrs.each do |vr|
-
case params["ruling_decision_#{vr.id}".to_sym]
-
when ValidationRuling::UNAPPROVED
-
vr.unapprove! unless vr.unapproved?
-
vr.notes.create(:title=>ValidationRuling::UNAPPROVED,
-
:note=>params["ruling_reason_#{vr.id}".to_sym], :user=>current_user)
-
@co.site_seal.deactivate! unless @co.site_seal.deactivated?
-
when ValidationRuling::MORE_REQUIRED
-
vr.require_more! unless vr.more_required?
-
vr.notes.create(:title=>ValidationRuling::MORE_REQUIRED,
-
:note=>params["ruling_reason_#{vr.id}".to_sym], :user=>current_user)
-
@co.site_seal.deactivate! unless @co.site_seal.deactivated?
-
when ValidationRuling::APPROVED
-
vr.approve! unless vr.approved?
-
vr.notes.create(:title=>ValidationRuling::APPROVED,
-
:note=>'requirement for "'+vr.
-
validation_rule.description+'" has been met.', :user=>current_user)
-
@co.site_seal.fully_activate! unless
-
@co.site_seal.fully_activated?
-
end
-
end
-
-
is_validated = false
-
if params[:validation_complete]
-
cc.validate! unless cc.validated?
-
is_validated = true
-
else
-
if vrs.all?(&:approved?)
-
unless cc.validated?
-
cc.validate! if !cc.issued?
-
is_validated = true
-
end
-
else
-
unless cc.pending_validation?
-
cc.pend_validation!(host: request.host_with_port)
-
is_validated = true
-
end
-
end
-
end
-
-
notify_customer(vrs) if params[:email_customer]
-
#include the username making this adjustment
-
vr_json = @validation.to_json.chop << ',"by_user":"' +
-
current_user.login + '","is_validated":"' + is_validated.to_s + '"}'
-
format.js { render :json=>vr_json}
-
else
-
format.js { render :json=>@validation.errors.to_json}
-
end
-
end
-
end
-
-
def send_to_ca(options={})
-
co=CertificateOrder.find_by_ref(params[:certificate_order_id])
-
result = co.apply_for_certificate(params.merge(current_user: current_user))
-
unless options[:send_to_ca].blank? or [Ca::CERTLOCK_CA,Ca::SSLCOM_CA,Ca::MANAGEMENT_CA].include?(params[:ca])
-
co.certificate_content.pend_validation!(send_to_ca: false, host: request.host_with_port) if result.order_number && !co.certificate_content.pending_validation?
-
end
-
respond_to do |format|
-
format.js {render :json=>{:result=>render_to_string(:partial=>
-
'sent_ca_result', locals: {ca_response: result})}}
-
end
-
end
-
-
def send_callback
-
returnObj = {}
-
@certificate_order = CertificateOrder.find_by_ref(params['certificate_order_id'])
-
-
if current_user
-
if @certificate_order
-
# Generate Token
-
co_token = CertificateOrderToken.new
-
co_token.certificate_order = @certificate_order
-
co_token.ssl_account = @certificate_order.ssl_account
-
co_token.user = current_user
-
co_token.is_expired = false
-
co_token.due_date = 7.days.from_now
-
co_token.token = (SecureRandom.hex(8)+Time.now.to_i.to_s(32))[0..19]
-
co_token.phone_verification_count = 0
-
co_token.phone_call_count = 0
-
co_token.status = CertificateOrderToken::PENDING_STATUS
-
co_token.save!
-
-
# Send callback email
-
params['emails'].each do |email|
-
OrderNotifier.callback_send(@certificate_order, co_token.token, email).deliver
-
end
-
-
returnObj['status'] = 'success'
-
end
-
else
-
returnObj['status'] = 'no-user'
-
end
-
-
render :json => returnObj
-
end
-
-
def verification
-
@status = true
-
@token = params[:token]
-
-
# Get CertificateOrderToken Object using emailed token url.
-
@certificate_order_token = CertificateOrderToken.find_by_token(params[:token])
-
-
if @certificate_order_token
-
if @certificate_order_token.status == CertificateOrderToken::EXPIRED_STATUS
-
@status = false
-
flash[:error] = 'This token has been expired.'
-
elsif @certificate_order_token.status == CertificateOrderToken::FAILED_STATUS
-
@status = false
-
flash[:error] = 'This token has been failed.'
-
elsif @certificate_order_token.status == CertificateOrderToken::DONE_STATUS
-
@status = false
-
flash[:error] = 'This token has been used before.'
-
else
-
if @certificate_order_token.due_date < DateTime.now
-
@certificate_order_token.update_columns(
-
is_expired: true,
-
status: CertificateOrderToken::EXPIRED_STATUS
-
)
-
@status = false
-
flash[:error] = 'This token has been expired.'
-
else
-
passed_token = (SecureRandom.hex(8)+params[:token])[0..19]
-
@certificate_order_token.update_column :passed_token, passed_token
-
-
# Get phone number and country from locked_registrant of certificate_order.
-
phone_number = @certificate_order_token.certificate_order.locked_registrant.phone || ''
-
country_code = @certificate_order_token.certificate_order.locked_registrant.country_code || '1'
-
@mobile_number = "(+" + country_code + ") " + phone_number
-
-
# Get all timezone
-
@time_zones = ActiveSupport::TimeZone.all
-
.map{|tz| ["(GMT#{formatted_offset(Timezone[tz.tzinfo.name].utc_offset)}) #{tz.name}" , (Timezone[tz.tzinfo.name].utc_offset / 3600).to_s + ':' + tz.tzinfo.name]}
-
.sort_by{|e| e[1].split(':')[0].to_i}
-
-
if @certificate_order_token.callback_type == CertificateOrderToken::CALLBACK_SCHEDULE
-
@callback_type = 'schedule'
-
@callback_method = @certificate_order_token.callback_method.upcase
-
@callback_datetime = @certificate_order_token.callback_datetime.in_time_zone(@certificate_order_token.callback_timezone.split(':')[1]).strftime('%Y-%m-%d %I:%M %p %:z')
-
@callback_locale = @certificate_order_token.locale.blank? ? 'en' : @certificate_order_token.locale
-
-
flash[:notice] = 'It has been already scheduled automated callback.'
-
elsif @certificate_order_token.callback_type == CertificateOrderToken::CALLBACK_MANUAL
-
@callback_type = 'manual'
-
@callback_method = @certificate_order_token.callback_method.upcase
-
@callback_datetime = @certificate_order_token.callback_datetime.in_time_zone(@certificate_order_token.callback_timezone.split(':')[1]).strftime('%Y-%m-%d %I:%M %p %:z')
-
@callback_locale = @certificate_order_token.locale.blank? ? 'en' : @certificate_order_token.locale
-
-
flash[:notice] = 'It has been already scheduled manual callback.'
-
else
-
@callback_type = 'none'
-
@callback_locale = 'en'
-
end
-
end
-
end
-
else
-
@status = false
-
flash[:error] = 'It is untrustworthy token.'
-
end
-
end
-
-
def automated_call
-
returnObj = {}
-
-
# if current_user
-
co_token = CertificateOrderToken.where(
-
token: params[:token],
-
status: CertificateOrderToken::PENDING_STATUS
-
).first
-
-
if co_token
-
phone_call_count = co_token.phone_call_count.nil? ? 0 : co_token.phone_call_count.to_i
-
if phone_call_count >= CertificateOrderToken::PHONE_CALL_LIMIT_MAX_COUNT
-
co_token.update_column :status, CertificateOrderToken::FAILED_STATUS
-
returnObj['status'] = 'reached_to_max'
-
else
-
# Generate new passed token.
-
passed_token = (SecureRandom.hex(8)+co_token.passed_token)[0..19]
-
co_token.update_column :passed_token, passed_token
-
-
# Increase phone call count.
-
phone_call_count = co_token.phone_call_count.to_i + 1
-
co_token.update_column :phone_call_count, phone_call_count
-
-
# Get phone number and country from locked_registrant of certificate_order.
-
phone_number = co_token.certificate_order.locked_registrant.phone || ''
-
country_code = co_token.certificate_order.locked_registrant.country_code || '1'
-
-
# # Get dial code from country.
-
# country_code = ISO3166::Country.new(country).country_code
-
-
@response = Authy::PhoneVerification.start(
-
via: params[:method],
-
country_code: country_code,
-
phone_number: phone_number,
-
locale: params[:locale]
-
)
-
-
if @response.ok?
-
returnObj['passed_token'] = passed_token
-
returnObj['status'] = 'success'
-
else
-
returnObj['status'] = 'failed'
-
end
-
end
-
else
-
returnObj['status'] = 'incorrect-token'
-
end
-
# else
-
# returnObj['status'] = 'no-user'
-
# end
-
-
render :json => returnObj
-
end
-
-
def phone_verification_check
-
returnObj = {}
-
-
# if current_user
-
co_token = CertificateOrderToken.where(
-
token: params[:token],
-
passed_token: params[:passed_token],
-
status: CertificateOrderToken::PENDING_STATUS
-
).first
-
-
if co_token
-
phone_verification_count = co_token.phone_verification_count.nil? ? 0 : co_token.phone_verification_count.to_i
-
if phone_verification_count >= CertificateOrderToken::PHONE_VERIFICATION_LIMIT_MAX_COUNT
-
co_token.update_column :status, CertificateOrderToken::FAILED_STATUS
-
returnObj['status'] = 'reached_to_max'
-
else
-
# Generate new passed token.
-
passed_token = (SecureRandom.hex(8)+params[:passed_token])[0..19]
-
co_token.update_column :passed_token, passed_token
-
-
# Increase phone verification count.
-
phone_verification_count = co_token.phone_verification_count.to_i + 1
-
co_token.update_column :phone_verification_count, phone_verification_count
-
-
# Get phone number and country from locked_registrant of certificate_order.
-
phone_number = co_token.certificate_order.locked_registrant.phone || ''
-
country_code = co_token.certificate_order.locked_registrant.country_code || '1'
-
-
# # Get dial code for country
-
# country_code = ISO3166::Country.new(country).country_code
-
-
@response = Authy::PhoneVerification.check(
-
verification_code: params[:phone_verification_code],
-
country_code: country_code,
-
phone_number: phone_number
-
)
-
-
if @response.ok?
-
phone_number = '+' + country_code + '-' + phone_number
-
co_token.update_columns(status: CertificateOrderToken::DONE_STATUS, phone_number: phone_number)
-
# TODO: After add info_verified state to workflow on certificate content, it should be commented out.
-
# co_token.certificate_order.certificate_content.validate!
-
-
returnObj['status'] = 'success'
-
else
-
returnObj['passed_token'] = passed_token
-
returnObj['status'] = 'failed'
-
end
-
end
-
else
-
returnObj['status'] = 'incorrect-token'
-
end
-
# else
-
# returnObj['status'] = 'no-user'
-
# end
-
-
render :json => returnObj
-
end
-
-
def register_callback
-
returnObj = {}
-
-
co_token = CertificateOrderToken.where(
-
token: params[:token],
-
status: CertificateOrderToken::PENDING_STATUS
-
).first
-
-
dtz = DateTime.strptime(
-
params[:callback_date] + ' ' + params[:callback_time] + ' ' + (params[:callback_timezone].split(':')[0].include?('-') ? '' : '+') + params[:callback_timezone].split(':')[0],
-
'%m/%d/%Y %I:%M %p %:z'
-
)
-
-
if co_token
-
co_token.update_columns(
-
callback_method: params[:callback_method],
-
callback_type: params[:callback_type],
-
callback_timezone: params[:callback_timezone],
-
callback_datetime: dtz,
-
is_callback_done: (params[:callback_type] == CertificateOrderToken::CALLBACK_MANUAL ? nil : false),
-
locale: params[:locale]
-
)
-
-
if params[:callback_type] == CertificateOrderToken::CALLBACK_MANUAL
-
OrderNotifier.manual_callback_send(co_token.certificate_order, dtz.strftime('%Y-%m-%d %I:%M %p %z')).deliver
-
returnObj['status'] = 'success-manual'
-
else
-
returnObj['status'] = 'success-schedule'
-
end
-
-
returnObj['callback_method'] = params[:callback_method].upcase
-
returnObj['callback_datetime'] = dtz.strftime('%Y-%m-%d %I:%M %p %:z')
-
-
else
-
returnObj['status'] = 'incorrect-token'
-
end
-
-
render :json => returnObj
-
end
-
-
def request_approve_phone_number
-
returnObj = {}
-
-
if current_user
-
super_users = User.search_super_user.uniq
-
super_users.each do |super_user|
-
OrderNotifier.request_phone_number_approve(@certificate_order, super_user.email).deliver
-
end
-
-
returnObj['status'] = 'success'
-
else
-
returnObj['status'] = 'session_expired'
-
end
-
-
render :json => returnObj
-
end
-
-
def cancel_validation_process
-
returnObj = {}
-
co = (current_user.is_system_admins? ? CertificateOrder :
-
current_user.certificate_orders).find_by_ref(params[:certificate_order_id])
-
-
if co
-
if co.certificate_contents.size == 0
-
returnObj['status'] = 'no-exist-cert-content'
-
else
-
co.certificate_content.destroy
-
if co.certificate_contents.size == 0
-
cc=CertificateContent.new
-
cc.certificate_order=co
-
cc.save
-
end
-
returnObj['status'] = 'success'
-
end
-
else
-
returnObj['status'] = 'no-exist-cert-order'
-
end
-
-
render :json => returnObj
-
end
-
-
private
-
-
def set_row_page
-
preferred_row_count = current_user.preferred_validate_row_count
-
@per_page = params[:per_page] || preferred_row_count.or_else("10")
-
CertificateOrder.per_page = @per_page if CertificateOrder.per_page != @per_page
-
-
if @per_page != preferred_row_count
-
current_user.preferred_validate_row_count = @per_page
-
current_user.save(validate: false)
-
end
-
-
@p = {page: (params[:page] || 1), per_page: @per_page}
-
end
-
-
def formatted_offset(seconds)
-
format = '%s%02d:%02d'
-
-
sign = (seconds < 0 ? '-' : '+')
-
hours = seconds.abs / 3600
-
minutes = (seconds.abs % 3600) / 60
-
format % [sign, hours, minutes]
-
end
-
-
def upload_documents(files, type=:validation)
-
i=0
-
@zip_file_name = ""
-
-
files.each do |file|
-
@created_releases = []
-
if (file.respond_to?(:content_type) && file.content_type.include?("zip")) ||
-
(file.respond_to?(:original_filename) && file.original_filename.include?("zip"))
-
logger.info "creating directory #{Rails.root}/tmp/zip/temp"
-
FileUtils.mkdir_p "#{Rails.root}/tmp/zip/temp" if !File.exist?("#{Rails.root}/tmp/zip/temp")
-
if file.size > Settings.max_content_size.to_i.megabytes
-
break @error = <<-EOS
-
Too Large: zip file #{file.original_filename} is larger than
-
#{help.number_to_human_size(Settings.max_content_size.to_i.megabytes)}
-
EOS
-
end
-
@zip_file_name=file.original_filename
-
File.open("#{Rails.root}/tmp/zip/#{file.original_filename}", "wb") do |f|
-
f.write(file.read)
-
end
-
zf = Zip::ZipFile.open("#{Rails.root}/tmp/zip/#{file.original_filename}")
-
if zf.size > Settings.max_num_releases.to_i
-
break @error = <<-EOS
-
Too Many Files: zip file #{file.original_filename} contains more than
-
#{Settings.max_num_releases.to_i} files.
-
EOS
-
end
-
zf.each do |entry|
-
begin
-
fpath = File.join("#{Rails.root}/tmp/zip/temp/",entry.name.downcase)
-
if(File.exists?(fpath))
-
File.delete(fpath)
-
end
-
zf.extract(entry, fpath)
-
@created_releases << create_with_attachment(LocalFile.new(fpath), type)
-
i+=1
-
rescue Errno::ENOENT, Errno::EISDIR
-
@error = "Invalid contents: zip entries with directories not allowed"
-
break
-
ensure
-
if (File.exists?(fpath))
-
if File.directory?(fpath)
-
FileUtils.remove_dir fpath, :force=>true
-
else
-
FileUtils.remove_file fpath, :force=>true
-
end
-
end
-
@created_releases.each {|release| release.destroy} unless @error.blank?
-
end
-
end
-
File.delete(zf.name) if (File.exists?(zf.name))
-
@created_releases.each do |doc|
-
doc.errors.each{|attr,msg|
-
@error << "#{attr} #{msg}: " }
-
end
-
else
-
vh = create_with_attachment(LocalFile.new(file.path, file.original_filename), type)
-
vh.errors.each{|attr,msg|
-
@error << "#{attr} #{msg}: " }
-
i+=1 if vh
-
@error << "Error: Document for #{file.original_filename} was not
-
created. Please notify system admin at #{Settings.support_email}" unless vh
-
end
-
end
-
@i += i
-
end
-
-
def validation_stage_checkout_in_progress?
-
co.certificate_content.contacts_provided?
-
end
-
-
def build_other_party_validation
-
-
end
-
-
def create_with_attachment(file, type=:validation)
-
@val_history = ValidationHistory.new(document: file)
-
unless type == :saved_registrant_documents
-
@certificate_order.validation.validation_histories << @val_history
-
end
-
@val_history.save
-
create_iv_attachment if type == :iv_documents
-
create_ov_attachment if type == :ov_documents
-
create_saved_registrant_attachment if type == :saved_registrant_documents
-
@val_history
-
end
-
-
def create_saved_registrant_attachment
-
if @val_history.valid? && params[:registrant_id]
-
@registrant = Registrant.find params[:registrant_id]
-
if @registrant
-
@registrant.validation_histories << @val_history
-
contacts = LockedRegistrant.where(parent_id: @registrant.id)
-
if contacts.any?
-
# If client or s/mime certificate used this registrant, then add
-
# documents to locked registrant and certificate order as well.
-
CertificateOrder.joins(certificate_contents: :locked_registrant)
-
.where("contacts.id IN (?)", contacts.ids).each do |co|
-
if co.certificate.is_smime_or_client?
-
co.locked_registrant.validation_histories << @val_history
-
co.validation.validation_histories << @val_history
-
end
-
end
-
end
-
end
-
end
-
end
-
-
def create_iv_attachment
-
if @val_history.valid?
-
iv_exists = @certificate_order.get_team_iv
-
if iv_exists
-
iv_exists.validation_histories << @val_history
-
lrc = @certificate_order.locked_recipient
-
if lrc && (lrc.user_id == iv_exists.user_id)
-
lrc.validation_histories << @val_history
-
end
-
end
-
end
-
end
-
-
def create_ov_attachment
-
if @val_history.valid?
-
lr = @certificate_order.locked_registrant
-
unless lr.nil?
-
lr.validation_histories << @val_history
-
if lr.parent_id
-
reusable_registrant = Registrant.find_by(id: lr.parent_id)
-
end
-
if reusable_registrant
-
reusable_registrant.validation_histories << @val_history
-
end
-
end
-
end
-
end
-
-
def find_validation
-
@validation=
-
if params[:id]
-
Validation.find(params[:id])
-
elsif params[:certificate_order_id]
-
CertificateOrder.find_by_ref(params[:certificate_order_id]).try(:validation)
-
end
-
render :text => "404 Not Found", :status => 404 unless @validation
-
end
-
-
def notify_customer(validation_rulings)
-
recips = [@co.certificate_content.administrative_contact]
-
recips << @co.certificate_content.validation_contact if
-
@co.certificate_content.validation_contact and @co.certificate_content.validation_contact.email.downcase!=
-
@co.certificate_content.administrative_contact.email.downcase
-
recips.each do |c|
-
if validation_rulings.all?(&:approved?)
-
OrderNotifier.validation_approve(c, @co).deliver
-
else
-
OrderNotifier.validation_unapprove(c, @co, @validation).deliver
-
end
-
end
-
end
-
-
def find_certificate_order
-
@certificate_order = (current_user.is_system_admins? ? CertificateOrder : current_user.certificate_orders).find_by_ref(params[:certificate_order_id])
-
@validation = @certificate_order.validation if @certificate_order
-
end
-
-
# def domain_validation
-
# byebug
-
# @exist_ext_order_number = @certificate_order.external_order_number
-
# if @exist_ext_order_number
-
# mdc_validation = ComodoApi.mdc_status(@certificate_order)
-
# # sdc_validation = ComodoApi.collect_ssl(@certificate_order)
-
# @ds = mdc_validation.domain_status
-
# end
-
# end
-
-
# source should be a zip file.
-
# target should be a directory to output the contents to.
-
-
def unzip_file(source, target)
-
# Create the target directory.
-
# We'll ignore the error scenario where
-
begin
-
Dir.mkdir(target) unless File.exists? target
-
end
-
-
Zip::ZipFile.open(source) do |zipfile|
-
dir = zipfile.dir
-
-
dir.entries('.').each do |entry|
-
zipfile.extract(entry, "#{target}/#{entry}")
-
end
-
end
-
rescue Zip::ZipDestinationFileExistsError => ex
-
# I'm going to ignore this and just overwrite the files.
-
rescue => ex
-
puts ex
-
end
-
-
def help
-
Helpers.instance
-
end
-
-
def set_supported_languages
-
@supported_languages = [
-
['Afrikaans', 'af'],
-
['Arabic', 'ar'],
-
['Catalan', 'ca'],
-
['Chinese', 'zh'],
-
['Chinese (Mandarin)', 'zh-CN'],
-
['Chinese (Cantonese)', 'zh-HK'],
-
['Croatian', 'hr'],
-
['Czech', 'cs'],
-
['Danish', 'da'],
-
['Dutch', 'nl'],
-
['English', 'en'],
-
['Finnish', 'fi'],
-
['French', 'fr'],
-
['German', 'de'],
-
['Greek', 'el'],
-
['Hebrew', 'he'],
-
['Hindi', 'hi'],
-
['Hungarian', 'hu'],
-
['Indonesian', 'id'],
-
['Italian', 'it'],
-
['Japanese', 'ja'],
-
['Korean', 'ko'],
-
['Malay', 'ms'],
-
['Norwegian', 'nb'],
-
['Polish', 'pl'],
-
['Portuguese - Brazil', 'pt-BR'],
-
['Portuguese', 'pt'],
-
['Romanian', 'ro'],
-
['Russian', 'ru'],
-
['Spanish', 'es'],
-
['Swedish', 'sv'],
-
['Tagalog', 'tl']
-
]
-
end
-
end
-
1
module AffiliatesHelper
-
1
def build_affiliate_links
-
@photos_count = @affiliate.photos.count
-
@posts_count = @affiliate.posts.count
-
@affiliate_links = affiliate_links #affiliate_photos+affiliate_blogs
-
end
-
-
1
def affiliate_links
-
link_to("Images (#{@photos_count})".l, affiliate_affiliate_photos_path(@affiliate)) +" \• " +
-
link_to("Blog Postings (#{@posts_count})".l, affiliate_posts_path(@affiliate))
-
end
-
-
1
def affiliate_photos
-
((link_to("Images (#{@photos_count})".l, affiliate_affiliate_photos_path(@affiliate)) +
-
((@posts_count > 0) ? " \• " : " ")) if
-
@photos_count > 0) || ""
-
end
-
-
1
def affiliate_blogs
-
((link_to("Blog Postings (#{@posts_count})".l, affiliate_posts_path(@affiliate))) if @posts_count > 0) || ""
-
end
-
end
-
# Methods added to this helper will be available to all templates in the application.
-
1
module ApplicationHelper
-
1
require 'memoist'
-
1
require 'string'
-
1
require 'object'
-
1
extend Memoist
-
-
# from Dan Webb's MinusMOR plugin
-
1
def js(data)
-
if data.respond_to? :to_json
-
data.to_json
-
else
-
data.inspect.to_json
-
end
-
end
-
-
1
def sandbox_notice
-
flash[:sandbox] = "SSL.com Sandbox. This is a test environment for api orders. Transactions and orders are not live."
-
end
-
-
# http://excid3.com/blog/change-actionmailer-email-url-host-dynamically
-
1
def set_mailer_host
-
host = if Rails.const_defined?('Console')
-
Settings.actionmailer_host
-
elsif is_sandbox_or_test?
-
'sandbox.ssl.com'
-
elsif request.host_with_port=="sws.sslpki.com"
-
'secure.ssl.com'
-
else
-
request.host_with_port
-
end
-
ActionMailer::Base.default_url_options[:host] = host
-
ActionMailer::Base.default_url_options[:protocol] = 'https'
-
end
-
-
# https://stackoverflow.com/questions/1602901/rails-separate-database-per-subdomain
-
# I use the entire domain, just change to sandbox_db and pass only the subdomain
-
1
def current_website
-
@website ||= Website.current_site(request.host) #this is causing issues when using sandbox and www on the same machine
-
# @website = Website.current_site(request.host)
-
end
-
1
memoize :current_website
-
-
1
def set_database
-
is_sandbox? ? current_website.use_database : Website.revert_database
-
sandbox_notice if @website.instance_of?(Sandbox) and self.is_a?(ApplicationController)
-
end
-
-
1
def is_sandbox?
-
@is_sandbox ||= Rails.cache.fetch("#{request.try(:host)}/is_sandbox") do
-
Sandbox.exists?(request.try(:host))
-
end
-
end
-
# memoize "is_sandbox?".to_sym
-
-
1
def is_sandbox_or_test?
-
is_sandbox? or ActionMailer::Base.default_url_options[:host]=~/^sandbox\./ or
-
ActionMailer::Base.default_url_options[:host]=~/^sws-test\./
-
end
-
-
1
def api_domain(certificate_order=nil)
-
api_source=@website || Settings
-
unless certificate_order.blank?
-
if Rails.env=~/production/i
-
"https://" + (certificate_order.is_test ? api_source.test_api_domain : api_source.api_domain)
-
else
-
"https://" + (certificate_order.is_test ? api_source.dev_test_api_domain : api_source.dev_api_domain) +":3000"
-
end
-
else
-
if is_sandbox?
-
Rails.env=~/production/i ? "https://#{api_source.test_api_domain}" : "https://#{api_source.dev_test_api_domain}:3000"
-
else
-
Rails.env=~/production/i ? "https://#{api_source.api_domain}" : "https://#{api_source.dev_api_domain}:3000"
-
end
-
end
-
end
-
-
1
def adjusted_position(position, certificate_order)
-
position-(CertificateOrder::FULL_SIGNUP_PROCESS[:pages].count -
-
certificate_order.signup_process[:pages].count)
-
end
-
-
1
def show_short_links?
-
false
-
end
-
-
# from Dan Webb's MinusMOR plugin
-
# enhanced with ability to detect partials with template format, i.e.: _post.html.erb
-
1
def partial(name, options={})
-
old_format = self.template_format
-
self.template_format = :html
-
js render({ :partial => name }.merge(options))
-
ensure
-
self.template_format = old_format
-
end
-
-
1
def logged_in_or_front_page
-
current_user && !current_page?(:controller=>:site, :action=>:index)
-
end
-
-
1
def photo_path(photo)
-
if photo.is_a? Photo
-
user_photo_path(photo.user, photo)
-
elsif photo.is_a? StudioPhoto
-
studio_studio_photo_path(photo.studio, photo)
-
elsif photo.is_a? AffiliatePhoto
-
affiliate_affiliate_photo_path(photo.affiliate, photo)
-
end
-
end
-
-
1
def image_url(source, timestamp=true)
-
abs_path = image_path(source)
-
unless abs_path =~ /\Ahttp/
-
abs_path = "http#{'s' if request.protocol =~ /https/}://#{request.host_with_port}#{abs_path}"
-
end
-
if timestamp
-
abs_path
-
else
-
abs_path.split('?')[0]
-
end
-
end
-
-
1
def selector(obj)
-
js "##{dom_id(obj)}"
-
end
-
-
1
def show_studio_only?
-
(@studio && Studio.exists?(@studio) &&
-
(current_page?(manage_video_sets_studio_releases_path(@studio)) ||
-
current_page?(manage_studio_releases_path(@studio)) ||
-
current_page?(studio_path(@studio)) ||
-
current_page?(studio_releases_path(@studio)))) ||
-
(@release && Release.exists?(@release) &&
-
current_page?(edit_release_path(@release.studio, @release)))
-
end
-
-
1
def text_field_for(form, field,
-
size=HTML_TEXT_FIELD_SIZE,
-
maxlength=DB_STRING_MAX_LENGTH, options = {})
-
form_field = form.text_field field, :size => size, :maxlength => maxlength, value: options[:value]
-
label = form.label(field, "#{'*' if options.delete(:required)}#{field.humanize}:".gsub(/\b\w/) {|s| s.upcase }) unless options.delete(:no_label)
-
append = yield if block_given?
-
create_tags label, form_field, options, append
-
end
-
-
1
def check_box_for(form, field, yes="1", no="0", options={})
-
form_field = form.check_box field, options, yes, no
-
label = form.label(field, "#{field.humanize}:".gsub(/\b\w/) {|s| s.upcase }) unless options.delete(:no_label)
-
append = yield if block_given?
-
create_tags label, form_field, options, append
-
end
-
-
1
def country_select_field_for(form, field, priority_countries = nil, options = {}, html_options = {})
-
#TODO needs fixing
-
#form_field = localized_country_select form.object_name, field, priority_countries, options, html_options
-
country_options = options_for_select(Country.select_options("name"), (options[:selected] || 'United States'))
-
if priority_countries
-
country_options = options_for_select(priority_countries+[""], disabled: [""])+country_options
-
end
-
form_field = select(form.object_name, field, country_options, options, html_options)
-
label = content_tag("label", "#{'*' if options.delete(:required)}#{field.humanize}:".gsub(/\b\w/) {|s| s.upcase }, :for => field) unless options.delete(:no_label)
-
append = yield if block_given?
-
create_tags label, form_field, options, append
-
end
-
-
1
def credit_card_select_field_for(form, field, options = {}, html_options = {})
-
form_field = form.select field, BillingProfile::CREDIT_CARDS, options, html_options
-
label = content_tag("label", "#{'*' if options.delete(:required)}#{field.humanize}:".gsub(/\b\w/) {|s| s.upcase }, :for => field) unless options.delete(:no_label)
-
append = yield if block_given?
-
create_tags label, form_field, options, append
-
end
-
-
1
def description_or_tagline(user)
-
user.is_a?(User)? user.description : user.tagline
-
end
-
-
1
def display_name(user)
-
user.is_a?(User)? user.login : user.display_name
-
end
-
-
1
def tree_list(channel)
-
base_finder = (filter_audience_type.blank?)? Release : Release.
-
scoped_by_audience_type(filter_audience_type)
-
@release_count = base_finder.all
-
@tree="<ul>"
-
channels = channel.camelcase.constantize.all :conditions => {:parent_id => nil}
-
channels.sort_by(&:name).each_with_object(@tree) do |channel, tree|
-
tree << ordered_list_for_tree(channel)
-
end
-
@tree<<"</ul>"
-
end
-
-
-
1
def closed_csr_prompt?
-
current_page?(controller: "certificates", action: "buy") && !@certificate_order.try(:has_csr)
-
end
-
-
1
def ordered_list_for_tree(channel)
-
"".tap do |tree|
-
unless channel.root?
-
tree << "<li>" << link_to(channel.name << ' (' << @release_count.select{|r|r.channel_id==channel.id}.size.to_s << ')', channel_path(channel)) << "</li>"
-
else
-
tree << "<li>" << link_to(channel.name << ' (' << @release_count.select{|r|[r.channel_id, r.channel.parent_id].include? channel.id }.size.to_s << ')', channel_path(channel))
-
unless channel.children.blank?
-
tree << "<ul>"
-
channel.children.each_with_object(tree) do |child, tree|
-
tree << ordered_list_for_tree(child)
-
end
-
tree << "</ul>"
-
end
-
tree << "</li>"
-
end
-
end
-
end
-
-
1
def select_field_for(form, field, choices, options = {}, html_options = {})
-
form_field = form.select(field, choices, options, html_options).html_safe
-
label = content_tag("label", "#{field.humanize}:".gsub(/\b\w/){|s|
-
s.upcase }, :for => field) unless options.delete(:no_label)
-
append = yield if block_given?
-
create_tags(label, form_field, options, append)
-
end
-
-
1
def add_to_cart_button(item)
-
if SERVER_SIDE_CART
-
button_to_function "Add to cart", remote_function(:url => {:controller =>
-
:orders, :action => :add, :id => item.model_and_id}), ({:disabled =>
-
"disabled"} if cart_items.include? item )
-
else
-
button_to_function("Add to cart", "$.add_remove_cart_items('add', {#{ShoppingCart::PRODUCT_CODE} :
-
'#{item.serial}'});$.adjust_items_in_cart();", :id => item.model_and_id,
-
:class => "add_to_cart_button", :disabled => (!current_user.blank? &&
-
current_user.owns_release(item))? true : false)
-
end
-
end
-
-
1
def remove_from_cart_link(item)
-
if SERVER_SIDE_CART
-
link_to_remote 'Remove', :url => {:controller => :orders, :action => :remove, :id => item.model_and_id}
-
else
-
link_to "Remove", '#', onclick: { :id => item.model_and_id}, :class => "remove_from_cart_link"
-
end
-
end
-
-
#Copied from /vendor/plugins/community_engine/engine_plugin/tiny_mce/lib/tiny_mce_helper.rb
-
#because it somehow skips loading tiny_mce_helper
-
1
def tiny_mce_init(options = @tiny_mce_options)
-
options ||= {}
-
default_options = {:mode => 'textareas',
-
:theme => 'simple'}
-
options = default_options.merge(options)
-
TinyMCE::OptionValidator.plugins = options[:plugins]
-
tinymce_js = "tinyMCE.init({\n"
-
i = 0
-
options.stringify_keys.sort.each do |pair|
-
key, value = pair[0], pair[1]
-
raise InvalidOption.new("Invalid option #{key} passed to tinymce") unless TinyMCE::OptionValidator.valid?(key)
-
tinymce_js += "#{key} : "
-
case value
-
when String, Symbol, Fixnum
-
tinymce_js += "'#{value}'"
-
when Array
-
tinymce_js += '"' + value.join(',') + '"'
-
when TrueClass
-
tinymce_js += 'true'
-
when FalseClass
-
tinymce_js += 'false'
-
else
-
raise InvalidOption.new("Invalid value of type #{value.class} passed for TinyMCE option #{key}")
-
end
-
(i < options.size - 1) ? tinymce_js += ",\n" : "\n"
-
i += 1
-
end
-
tinymce_js += "\n});"
-
javascript_tag tinymce_js
-
end
-
1
alias tiny_mce tiny_mce_init
-
-
1
def using_tiny_mce?
-
!@uses_tiny_mce.nil?
-
end
-
-
1
def javascript_include_tiny_mce
-
javascript_include_tag RAILS_ENV == 'development' ? "tiny_mce/tiny_mce_src" : "tiny_mce/tiny_mce", :plugin => "community_engine"
-
end
-
-
1
def javascript_include_tiny_mce_if_used
-
javascript_include_tiny_mce if @uses_tiny_mce
-
end
-
-
1
def render_activation_messages
-
assignments = current_user.assignments.where.not(role_id: Role.cannot_be_invited) if current_user
-
if assignments && assignments.any?
-
teams = current_user.ssl_account_users
-
.where(ssl_account_id: assignments.map(&:ssl_account).uniq.compact.map(&:id))
-
.where.not(approved: false).where(declined_at: nil).map(&:ssl_account).uniq.compact
-
count = teams.count
-
tab = ' ' * 5
-
@notice = [
-
"In addition to activating your own account, you're a member of #{count} other #{'team'.pluralize(count)}.",
-
"You can switch teams by clicking on a team name in <strong>CURRENT TEAM</strong> in the top menu.",
-
"You can also visit <strong>#{link_to 'Teams', teams_user_path(current_user)}</strong> page to manage all teams.<br />",
-
"Invited to Teams (#{count})<br />"
-
]
-
teams.each do |team|
-
switch_link = link_to(team.get_team_name.upcase, switch_default_ssl_account_user_path(current_user, ssl_account_id: team.id))
-
@notice << "#{tab}Team: <strong>#{switch_link}</strong>"
-
@notice << "#{tab}Roles: <strong>#{current_user.roles_humanize(team).join(', ')}</strong><br />"
-
end
-
roles = assignments.map(&:role).uniq
-
if roles.any?
-
@notice << "Role Descriptions<br />"
-
roles.each {|role| @notice << "<strong>#{role.name.humanize(capitalize: false)}:</strong> #{role.description}" if role.description}
-
end
-
@notice
-
end
-
end
-
-
#
-
# Index Columns Sorting and Filter Helpers
-
#
-
1
def filter_operators_list
-
[
-
[nil, nil],
-
["Equal To", "equal"],
-
["Less than", "less_than"],
-
["Less or equal", "less_or_equal"],
-
["Greater than", "greater_than"],
-
["Greater or equal", "greater_or_equal"]
-
]
-
end
-
-
1
def sort_link(column, direction, title)
-
icon = sort_icon_for(column)
-
direction = if direction.blank?
-
'asc'
-
else
-
direction == 'asc' ? 'desc' : 'asc'
-
end
-
-
link_to "#{title} #{icon}".html_safe,
-
get_full_path(
-
params.merge(column: column, direction: direction).permit!
-
),
-
class: 'tbl-sortable-column'
-
end
-
-
1
def sort_params_for(column)
-
direction = params[:direction] == 'asc' ? 'desc' : 'asc'
-
params.except(:controller, :action).merge(column: column, direction: direction, page: 1).permit!
-
end
-
-
1
def sort_icon_for(column)
-
return if column.to_s != params[:column] || params[:direction].blank?
-
params[:direction] == 'asc' ? '↑' : '↓'
-
end
-
-
1
def get_col_direction(column, params)
-
column == params[:column] ? params[:direction] : ''
-
end
-
-
1
def render_user_roles(roles_list)
-
final = []
-
roles_list.each do |role|
-
icon = case role
-
when :billing, 'billing' then 'dollar'
-
when :validations, 'validations' then 'expeditedssl'
-
when :installer, 'installer' then 'download'
-
when :users_manager, 'users_manager' then 'id-card'
-
when :individual_certificate, 'individual_certificate' then 'certificate'
-
when :owner, 'owner' then 'user-circle'
-
when :reseller, 'reseller' then 'window-restore'
-
else 'cog'
-
end
-
str_role = role == :individual_certificate ? 'indiv_certificate' : role.to_s
-
final << "<i class='fa fa-#{icon}'></i> #{str_role}<br/>"
-
end
-
final.join('').html_safe
-
end
-
-
1
def get_mailbox_folder_path
-
case @email_type
-
when :inbox
-
mail_inbox_path(@ssl_slug)
-
when :sent
-
mail_sent_path(@ssl_slug)
-
else
-
mail_trash_path(@ssl_slug)
-
end
-
end
-
-
1
private
-
-
1
def create_tags(label, form_field, options, append)
-
tag_class = options.delete :class
-
required = options.delete :required
-
format = options.delete :format
-
asterisk = (required)?"*":""
-
append ||= ""
-
case format
-
when /table/
-
content_tag("th", "#{label}#{asterisk}", nil, false) +
-
content_tag("td","#{form_field}#{append}", nil, false)
-
when /no_div/
-
"#{label}#{asterisk} #{form_field}#{append}".html_safe
-
else
-
content_tag("div", "#{label}#{asterisk} #{form_field}#{append}",
-
{:class => tag_class}, false)
-
end
-
end
-
-
1
def cookie_domain
-
Rails.env.development? ? "ssl.local" : "ssl.com"
-
end
-
-
1
def set_cookie_js(name,value)
-
"$.cookie(\"#{name}\", #{value}, {path: '/',domain: \".#{cookie_domain}\"})"
-
end
-
-
1
def srp_link
-
link_to "SSL Reseller Program", details_resellers_url(subdomain: Reseller::SUBDOMAIN)
-
end
-
-
1
def link_to_remove_fields(name, f)
-
f.hidden_field(:_destroy) + link_to(name, '#', onclick: "remove_fields(this)")
-
end
-
-
1
def link_to_add_fields(name, f, association)
-
new_object = f.object.class.reflect_on_association(association).klass.new
-
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
-
render(association.to_s.singularize + "_fields", :f => builder)
-
end
-
link_to(name, '#', onclick: h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))
-
end
-
-
1
def skip_payment?
-
order_paid = @certificate_order.order.blank? ? false : @certificate_order.order.paid?
-
start_over = (@certificate_order.certificate_contents.count>1)
-
cc=@certificate_order.certificate_content
-
!!(@certificate_order.is_prepaid? || (order_paid && start_over) ||
-
(eval("@#{CertificateOrder::REPROCESSING}") || (cc && cc.preferred_reprocessing?)))
-
end
-
-
1
def order_progress_indicator(page, certificate)
-
co=@certificate_order
-
sv=co.certificate ? co.skip_verification? : CertificateOrder.skip_verification?(certificate)
-
added_padding=1.54
-
process = if params[:order_description] || (params[:reprocess_ucc] ||
-
(co.certificate && co.certificate.is_ucc? &&
-
(co.order.reprocess_ucc_order? || params[:action] == "reprocess")))
-
-
co.reprocess_ucc_process
-
elsif certificate && certificate.is_smime_or_client?
-
co.smime_client_process
-
else
-
skip_payment? ? co.prepaid_signup_process(certificate) : co.signup_process(certificate)
-
end
-
padding = case process
-
when CertificateOrder::EXPRESS_SIGNUP_PROCESS, CertificateOrder::PREPAID_FULL_SIGNUP_PROCESS
-
"padding: 0 #{1.4 + (sv ? added_padding : 0.0)}em"
-
when CertificateOrder::FULL_SIGNUP_PROCESS
-
"padding: 0 #{0.5 + (sv ? added_padding : 0.0)}em"
-
when CertificateOrder::PREPAID_EXPRESS_SIGNUP_PROCESS
-
"padding: 0 #{2.9 + (sv ? added_padding : 0.0)}em"
-
when CertificateOrder::REPROCES_SIGNUP_W_PAYMENT, CertificateOrder::CLIENT_SMIME_VALIDATE
-
"padding: 0 #{0.5 + (sv ? added_padding : 0.0)}em"
-
when CertificateOrder::REPROCES_SIGNUP_W_INVOICE, CertificateOrder::CLIENT_SMIME_VALIDATED
-
"padding: 0 #{1.4 + (sv ? added_padding : 0.0)}em"
-
end
-
pages = sv ? process[:pages] - [CertificateOrder::VERIFICATION_STEP] : process[:pages]
-
process[:pages].delete('Contacts') if co.skip_contacts_step?
-
-
render(:partial => '/shared/form_progress_indicator',
-
:locals => {:pages=>[pages, page],
-
:options=>{:li_style=>padding}, certificate: certificate})
-
end
-
-
#this has been bastardized, need to come up with a 'cleaner' solution
-
1
def is_public_index_page?
-
current_page?(:controller=>:site, :action=>:index) ||
-
current_page?(:controller=>:site, :action=>:reseller) ||
-
current_page?(:controller=>:surls, :action=>:index) ||
-
current_page?(:controller=>:surls, :action=>:update) ||
-
current_page?(:controller=>:surls, :action=>:edit) ||
-
current_page?(:controller=>:surls, :action=>:show)
-
end
-
-
# If the current user meets the given privilege, permitted_to? returns true
-
# and yields to the optional block. The attribute checks that are defined
-
# in the authorization rules are only evaluated if an object is given
-
# for context.
-
#
-
# Examples:
-
# <% permitted_to? :create, :users do %>
-
# <%= link_to 'New', new_user_path %>
-
# <% end %>
-
# ...
-
# <% if permitted_to? :create, :users %>
-
# <%= link_to 'New', new_user_path %>
-
# <% else %>
-
# You are not allowed to create new users!
-
# <% end %>
-
# ...
-
# <% for user in @users %>
-
# <%= link_to 'Edit', edit_user_path(user) if permitted_to? :update, user %>
-
# <% end %>
-
#
-
# To pass in an object and override the context, you can use the optional
-
# options:
-
# permitted_to? :update, user, :context => :account
-
#
-
# def permitted_to? (privilege, object_or_sym = nil, options = {}, &block)
-
# controller.permitted_to?(privilege, object_or_sym, options, &block)
-
# end
-
-
# While permitted_to? is used for authorization in views, in some cases
-
# content should only be shown to some users without being concerned
-
# with authorization. E.g. to only show the most relevant menu options
-
# to a certain group of users. That is what has_role? should be used for.
-
#
-
# Examples:
-
# <% has_role?(:sales) do %>
-
# <%= link_to 'All contacts', contacts_path %>
-
# <% end %>
-
# ...
-
# <% if has_role?(:sales) %>
-
# <%= link_to 'Customer contacts', contacts_path %>
-
# <% else %>
-
# ...
-
# <% end %>
-
#
-
1
def has_role? (*roles, &block)
-
controller.has_role?(*roles, &block)
-
end
-
-
# As has_role? except checks all roles included in the role hierarchy
-
1
def has_role_with_hierarchy?(*roles, &block)
-
controller.has_role_with_hierarchy?(*roles, &block)
-
end
-
-
1
def message_for_item(message, item = nil)
-
return message unless item
-
if item.is_a?(Array)
-
message % link_to(*item)
-
else
-
message % item
-
end.html_safe
-
end
-
-
1
def remote_login_link(u)
-
link_to("login as #{u.login}", user_session_url(:login=>u.login,
-
authenticity_token: form_authenticity_token()), :method=>:post,
-
:id=>u.model_and_id) unless u.is_disabled?
-
end
-
-
1
def link_cluster(arry)
-
arry.compact.join(" | ").html_safe
-
end
-
-
1
def recert?
-
recert=nil
-
CertificateOrder::RECERTS.each do |r|
-
r_obj = instance_variable_get("@#{r}")
-
unless r_obj.blank?
-
recert=hidden_field_tag(r.to_sym, r_obj.ref)
-
break
-
end
-
end
-
recert
-
end
-
-
1
def is_new_order_page?
-
current_page?(new_order_path) || current_page?(checkout_orders_path)
-
end
-
-
1
def get_full_path(params)
-
path = params[:controller] == 'certificates' ? "admin_index_" : ''
-
send("#{path}#{params[:controller]}_path", params.except(:controller, :action))
-
end
-
-
1
def co_folder_children(contents, options={})
-
output = []
-
contents.includes{certificate_orders.certificate_contents}.each do |f|
-
output << FolderTree.new(
-
ssl_account_id: @ssl_account,
-
folder: f,
-
tree_type: @tree_type,
-
selected_ids: [],
-
certificate_order_ids: @certificate_order_ids,
-
folder_ids: params[:folder_ids]
-
).full_tree
-
end
-
output.to_json.html_safe
-
end
-
-
1
def show_folders_container?
-
params[:folders] || (params[:search] && params[:search].include?('folder_ids'))
-
end
-
end
-
1
module CertificateContentsHelper
-
end
-
1
module CertificateOrdersHelper
-
-
1
def render_certificate_durations
-
certificate_id = params[:certificate_id] || params[:certificate_enrollment_invite][:certificate_id]
-
@certificate = Certificate.find certificate_id
-
partial = render_to_string(
-
partial: 'certificate_orders/smime_client_enrollment/duration_form',
-
layout: false
-
)
-
render json: {content: partial}, status: :ok
-
end
-
-
1
def order_line_items(certificate_order, email_template=false, invoice=false)
-
items = []
-
if certificate_order.certificate.is_ucc? || certificate_order.certificate.is_wildcard?
-
soi = certificate_order.sub_order_items.detect{|item|item.
-
product_variant_item.is_server_license?}
-
unless soi.blank?
-
if soi.quantity>0
-
items << pluralize(soi.quantity+1, "server license")
-
end
-
if certificate_order.certificate.is_ucc?
-
reprocess_order = @order && @order.reprocess_ucc_order?
-
domains_adjustment = @order && @order.domains_adjustment? && !reprocess_order
-
reprocess_domains = @order.get_reprocess_domains if (reprocess_order || domains_adjustment)
-
-
quantity = (domains_adjustment || reprocess_order) ? reprocess_domains[:all].count : certificate_order.purchased_domains('all')
-
unless certificate_order.certificate_contents.empty?
-
d = reprocess_order ? reprocess_domains[:all] : certificate_order.all_domains
-
domains = d.blank? ? "" : d.join(", ")
-
wildcard_qty = reprocess_order ? reprocess_domains[:cur_wildcard] : certificate_order.purchased_domains('wildcard')
-
-
if email_template
-
items << "domains - " + (domains.empty? ? "" : "("+domains+")")
-
elsif invoice
-
items << pluralize(quantity, "#{certificate_order.certificate.is_premium_ssl? ? 'sub' : ''}domain") +
-
(wildcard_qty==0 ? '' : " (#{pluralize(wildcard_qty, 'wildcard ssl domain')})")
-
items << domains.split('+') unless domains.empty? || domains.blank?
-
else
-
items << content_tag(:dt,pluralize(quantity, "#{certificate_order.certificate.is_premium_ssl? ? 'sub' : ''}domain")+
-
(wildcard_qty==0 ? '' : " (#{pluralize(wildcard_qty, 'wildcard ssl domain')})")) +
-
(domains.empty? ? "" : content_tag(:dd,"("+domains+")"))
-
end
-
-
if (reprocess_order && reprocess_domains[:new_domains_count] > 0) || domains_adjustment
-
co_desc = invoice ? " For certificate order ##{certificate_order.ref}." : ''
-
descr = if @order.invoice_description.blank?
-
"Prorated charge for #{reprocess_domains[:new_domains_count]}
-
additional domains. (wildcard: #{reprocess_domains[:wildcard]},
-
non wildcard: #{reprocess_domains[:non_wildcard]})"
-
else
-
"#{@order.invoice_description} #{co_desc}"
-
end
-
items << content_tag(:strong, descr)
-
end
-
end
-
end
-
end
-
end
-
if !(certificate_order.certificate.is_client? || certificate_order.certificate.is_code_signing?)
-
items << "SSL.com Secured Seal"
-
items << link_to("SSL.com daily site monitoring", notification_groups_path({ssl_slug: @ssl_slug}))
-
end
-
items
-
end
-
-
1
def check_for_current_certificate_order
-
return false unless @certificate_order
-
end
-
-
1
def expires_on(certificate_content)
-
return "n/a" if certificate_content.csr.blank?
-
(certificate_content.new? ||
-
certificate_content.csr.signed_certificate.blank? ||
-
certificate_content.csr.signed_certificate.expiration_date.blank?)?
-
"n/a" : certificate_content.csr.signed_certificate.
-
expiration_date.strftime("%b %d, %Y")
-
end
-
-
1
def sandbox_notice
-
flash[:sandbox] = "SSL.com Sandbox. This is a test environment for api orders. Transactions and orders are not live."
-
end
-
-
1
def domains_adjust_billing?(certificate_order)
-
return false if certificate_order.nil? || certificate_order.new?
-
certificate_order.domains_adjust_billing?
-
end
-
-
1
def action(certificate_order)
-
certificate_content = certificate_order.certificate_contents.last
-
certificate = certificate_order.certificate
-
if certificate_content.new?
-
certificate_order.expired? ? "expired" :
-
link_to(certificate_order.certificate.admin_submit_csr? ? 'provide info' :
-
'submit csr', edit_certificate_order_path(@ssl_slug, certificate_order))
-
elsif certificate_order.expired?
-
link_to 'renew', renew_certificate_order_path(@ssl_slug, certificate_order)
-
else
-
case certificate_content.workflow_state
-
when "csr_submitted"
-
link_to('provide info', edit_certificate_order_path(@ssl_slug, certificate_order)) if
-
permitted_to?(:update, certificate_order)
-
when "info_provided"
-
link_to('provide contacts', certificate_content_contacts_path(@ssl_slug, certificate_content)) if
-
permitted_to?(:update, certificate_order)
-
when "reprocess_requested"
-
link_to('submit csr', edit_certificate_order_path(@ssl_slug, certificate_order)) if
-
permitted_to?(:update, certificate_order)
-
when "contacts_provided", "pending_validation", "validated"
-
if certificate_content.workflow_state == "validated" && (certificate.is_cs? || certificate.is_smime_or_client?)
-
specific_action(certificate, certificate_order, false)
-
# link_to 'generate certificate', generate_cert_certificate_order_path(@ssl_slug, certificate_order.ref) if
-
# permitted_to?(:update, certificate_order.validation) # assume multi domain
-
else
-
link_to certificate_order.certificate.admin_submit_csr? ? 'upload documents' : 'perform validation', new_certificate_order_validation_path(@ssl_slug, certificate_order) if
-
permitted_to?(:update, certificate_order.validation) # assume multi domain
-
end
-
when "issued","revoked"
-
if(certificate.is_cs? || certificate.is_smime_or_client?)
-
specific_action(certificate, certificate_order, true)
-
# link_to 'generate certificate', generate_cert_certificate_order_path(@ssl_slug, certificate_order.ref) if
-
# permitted_to?(:update, certificate_order.validation) # assume multi domain
-
else
-
if certificate_content.expiring?
-
if certificate_order.renewal && certificate_order.renewal.paid?
-
link_to('see renewal', certificate_order_path(@ssl_slug, certificate_order.renewal)) if
-
permitted_to?(:show, certificate_order)
-
elsif certificate_order.signed_certificate_duration_delta > 1
-
link_to('change domain(s)/rekey', reprocess_certificate_order_path(@ssl_slug,
-
certificate_order)) if permitted_to?(:update, certificate_order)
-
else
-
links = "<li>#{link_to 'renew', renew_certificate_order_path(@ssl_slug, certificate_order)}</li>"
-
links << "<li> or #{link_to 'change domain(s)/rekey', reprocess_certificate_order_path(@ssl_slug,
-
certificate_order)}</li>" if permitted_to?(:update, certificate_order) and
-
!certificate_content.expired?
-
"<ul>#{links}</ul>".html_safe
-
end
-
else
-
if certificate_order.certificate.is_free?
-
links = "<li>#{link_to 'upgrade', renew_certificate_order_path(@ssl_slug, certificate_order)}</li>"
-
links << "<li>or #{link_to 'change domain(s)/rekey',
-
reprocess_certificate_order_path(@ssl_slug, certificate_order)}</li>" if permitted_to?(:update,
-
certificate_order) and !certificate_content.expired?
-
"<ul>#{links}</ul>".html_safe
-
else
-
("<ul>"+(current_page?(certificate_order_path(@ssl_slug, certificate_order)) ? "" :
-
"<li>#{link_to 'download', certificate_order_path(@ssl_slug, certificate_order)} or </li>")+
-
((permitted_to?(:read, certificate_order) and !certificate_content.expired?) ?
-
"<li>#{link_to 'change domain(s)/rekey',
-
reprocess_certificate_order_path(@ssl_slug, certificate_order)}</li></ul>" : "")).html_safe
-
-
end
-
end
-
end
-
when "canceled"
-
end
-
end
-
end
-
-
1
def specific_action(certificate, certificate_order, is_rekey)
-
if current_user.is_individual_certificate? or
-
(certificate_order.get_recipient and certificate_order.get_recipient.email==current_user.email)
-
reset_expired_token_request_status(certificate_order)
-
-
if certificate_order.generate_certificate_order_token.blank? or certificate_order.generate_certificate_order_token.is_expired
-
if certificate.is_client_basic?
-
recipient = certificate_order.get_recipient
-
iv = Contact.find_by(user_id: (recipient.user_id || recipient.id))
-
certificate_order.update_attribute(:request_status, 'done')
-
-
link_to 'send activation link to ' + iv.email,
-
nil, class: 'link_to_send_notify',
-
:data => { :ref => certificate_order.ref,
-
:type => 'token',
-
:ori_text => '',
-
:done => 'false'
-
}
-
else
-
link_to certificate_order.request_status == 'done' ? 'activation request sent. Request again?' : (is_rekey ? 'request rekey' : 'request certificate'),
-
nil, class: 'link_to_send_notify',
-
:data => {
-
:ref => certificate_order.ref,
-
:type => 'request',
-
:done => certificate_order.request_status == 'done' ? 'true' : 'false'
-
}
-
end
-
else
-
if !certificate.is_client_basic? || (certificate.is_client_basic? && current_user.is_standard? && current_user.ssl_account.epki_registrant)
-
link_to 'generate certificate', confirm_path(certificate_order.generate_certificate_order_token.token) if
-
permitted_to?(:update, certificate_order.validation) # assume multi domain
-
else
-
recipient = certificate_order.get_recipient
-
iv = Contact.find_by(user_id: (recipient.user_id || recipient.id))
-
-
link_to 'activation link sent. Resend?',
-
nil, class: 'link_to_send_notify',
-
:data => { :ref => certificate_order.ref,
-
:type => 'token',
-
:ori_text => 'send activation link to ' + iv.email,
-
:done => 'true'
-
}
-
end
-
end
-
elsif current_user.is_billing_only? || current_user.is_validations_only? || current_user.is_validations_and_billing_only?
-
'n/a'
-
else
-
if certificate.is_smime_or_client? && certificate_order.get_recipient
-
reset_expired_token_request_status(certificate_order)
-
-
recipient = certificate_order.get_recipient
-
iv = Contact.find_by(user_id: (recipient.user_id || recipient.id))
-
link_to !certificate_order.generate_certificate_order_token.blank? && !certificate_order.generate_certificate_order_token.is_expired ?
-
'activation link sent. Resend?' : 'send activation link to ' + iv.email,
-
nil, class: 'link_to_send_notify',
-
:data => { :ref => certificate_order.ref,
-
:type => 'token',
-
:ori_text => ((!certificate_order.generate_certificate_order_token.blank? && !certificate_order.generate_certificate_order_token.is_expired) ?
-
('send activation link to ' + iv.email) : ''),
-
:done => (!certificate_order.generate_certificate_order_token.blank? && !certificate_order.generate_certificate_order_token.is_expired).to_s
-
}
-
elsif certificate_order.locked_registrant and certificate_order.certificate_content.ca
-
reset_expired_token_request_status(certificate_order)
-
-
link_to !certificate_order.generate_certificate_order_token.blank? && !certificate_order.generate_certificate_order_token.is_expired ?
-
'activation link sent. Resend?' : 'send activation link to ' + certificate_order.locked_registrant.email,
-
nil, class: 'link_to_send_notify',
-
:data => { :ref => certificate_order.ref,
-
:type => 'token',
-
:ori_text => ((!certificate_order.generate_certificate_order_token.blank? && !certificate_order.generate_certificate_order_token.is_expired) ?
-
('send activation link to ' + certificate_order.locked_registrant.email) : ''),
-
:done => (!certificate_order.generate_certificate_order_token.blank? && !certificate_order.generate_certificate_order_token.is_expired).to_s
-
}
-
else
-
'n/a'
-
end
-
end
-
end
-
-
1
def reset_expired_token_request_status(certificate_order)
-
if certificate_order.generate_certificate_order_token &&
-
!certificate_order.generate_certificate_order_token.is_expired &&
-
certificate_order.generate_certificate_order_token.due_date < DateTime.now
-
certificate_order.generate_certificate_order_token.update_attribute(:is_expired, true)
-
certificate_order.update_attribute(:request_status, '')
-
end
-
end
-
-
1
def other_party_request(certificate_order)
-
if current_user.blank?
-
return true
-
elsif current_user.is_admin?
-
return false
-
end
-
(certificate_order.ssl_account!=current_user.ssl_account)
-
end
-
-
1
def certificate_order_status(certificate_content=nil,co=nil)
-
return if certificate_content.blank?
-
co ||= certificate_content.cached_certificate_order
-
if co && certificate_content.new?
-
co.is_expired? ? 'expired' : (co.certificate.admin_submit_csr? ? 'info required' : 'waiting for csr')
-
elsif certificate_content.expired?
-
'expired'
-
elsif certificate_content.preferred_reprocessing?
-
'reprocess requested'
-
else
-
case certificate_content.workflow_state
-
when "csr_submitted"
-
'info required'
-
when "info_provided"
-
'contacts required'
-
when "reprocess_requested"
-
'csr required'
-
when "contacts_provided"
-
'validation required'
-
else
-
certificate_content.workflow_state.to_s.titleize.downcase
-
end
-
end
-
end
-
-
1
def status_class(certificate_content)
-
return 'attention' if certificate_content.new? ||
-
certificate_content.expired?
-
case certificate_content.workflow_state
-
when "csr_submitted", "info_provided", "reprocess_requested",
-
"contacts_provided"
-
'attention'
-
when "pending_validation"
-
'validation_waiting'
-
#give the green indicator. pondering on setting
-
#validated to validation_waiting
-
when "validated", "issued", "pending_issuance"
-
'validation_approved'
-
else
-
''
-
end
-
end
-
-
1
def expires_on_class(certificate_content,co=nil)
-
return if certificate_content.new? ||
-
certificate_content.csr.blank? ||
-
certificate_content.csr.signed_certificate.blank? ||
-
certificate_content.csr.signed_certificate.expiration_date.blank?
-
co ||= certificate_content.cached_certificate_order
-
if co.try(:ssl_account)
-
sa = co.ssl_account
-
ep = certificate_content.csr.signed_certificate.expiration_date
-
if ep <= sa.preferred_reminder_notice_triggers(ReminderTrigger.find(1)).
-
to_i.days.from_now && ep > Time.now
-
'expiration_warning'
-
elsif ep <= Time.now
-
'attention'
-
else
-
''
-
end
-
end
-
end
-
-
1
def certificate_type(certificate_order)
-
if certificate_order.is_a?(CertificateOrder)
-
unless Order.unscoped{certificate_order.order}.preferred_migrated_from_v2
-
certificate_order.certificate.description["certificate_type"]
-
else
-
certificate_order.preferred_v2_product_description.
-
gsub /[Cc]ertificate\z/, ''
-
end
-
end
-
end
-
-
1
def certificate_formats(csr, sc)
-
{iis7: ["Microsoft IIS (*.p7b)", pkcs7_csr_signed_certificate_url(@ssl_slug, csr, sc), SignedCertificate::IIS_INSTALL_LINK],
-
cpanel: ["WHM/cpanel", whm_zip_csr_signed_certificate_url(@ssl_slug, csr, sc), SignedCertificate::CPANEL_INSTALL_LINK],
-
apache: ["Apache", apache_zip_csr_signed_certificate_url(@ssl_slug, csr, sc), SignedCertificate::APACHE_INSTALL_LINK],
-
amazon: ["Amazon", amazon_zip_csr_signed_certificate_url(@ssl_slug, csr, sc), SignedCertificate::AMAZON_INSTALL_LINK],
-
nginx: ["Nginx", nginx_csr_signed_certificate_url(@ssl_slug, csr, sc), SignedCertificate::NGINX_INSTALL_LINK],
-
v8_nodejs: ["V8+Node.js", nginx_csr_signed_certificate_url(@ssl_slug, csr, sc), SignedCertificate::V8_NODEJS_INSTALL_LINK],
-
java: ["Java/Tomcat", download_csr_signed_certificate_url(@ssl_slug, csr, sc), SignedCertificate::JAVA_INSTALL_LINK],
-
other: ["Other platforms", download_csr_signed_certificate_url(@ssl_slug, csr, sc), SignedCertificate::OTHER_INSTALL_LINK],
-
bundle: ["CA bundle (intermediate certs)", server_bundle_csr_signed_certificate_url(@ssl_slug, csr, sc), SignedCertificate::OTHER_INSTALL_LINK]}
-
end
-
-
# When validation instructions are generated for a certificate name,
-
# remove "www" for Basic SSL, High Assurance SSL, and Enterprise EV SSL certs
-
# in the CN of the CSR
-
1
def render_domain_for_instructions(certificate_order, target_domain)
-
unless certificate_order.certificate.is_multi?
-
target_domain = target_domain.remove(/\Awww./)
-
end
-
target_domain
-
end
-
-
1
def for_ev?
-
@certificate_order.certificate.is_ev? unless ["ov","dv"].include?(params[:downstep])
-
end
-
-
# EV SSL can downstep to OV
-
1
def for_ov?
-
((@certificate_order.certificate.is_ov? or @certificate_order.certificate.is_naesb?) unless ["dv"].
-
include?(params[:downstep])) or downstepped_to_ov?
-
end
-
-
# EV and OV SSL can downstep to DV
-
1
def for_dv?
-
@certificate_order.certificate.is_dv? or downstepped_to_dv?
-
end
-
-
1
def downstepped_to_dv?
-
(@certificate_order.certificate.is_ev? or
-
@certificate_order.certificate.is_ov?) and params[:downstep]=="dv"
-
end
-
-
1
def downstepped_to_ov?
-
@certificate_order.certificate.is_ev? and params[:downstep]=="ov"
-
end
-
-
1
def downstepped_to_cs?
-
@certificate_order.certificate.is_evcs? and params[:downstep]=="cs"
-
end
-
-
1
def downstepped?
-
downstepped_to_cs? or downstepped_to_dv? or downstepped_to_ov?
-
end
-
-
1
def for_evcs?
-
@certificate_order.certificate.is_evcs? unless ["cs"].include?(params[:downstep])
-
end
-
-
# EV CS can downstep to CS
-
1
def for_cs?
-
@certificate_order.certificate.is_cs? or downstepped_to_cs?
-
end
-
end
-
1
module CertificatesHelper
-
1
def certificate_crumbs
-
crumb = link_to "ssl certificates", certificates_path
-
crumb << " :: "
-
if @certificate.is_ucc? || @certificate.is_wildcard?
-
crumb << link_to("wildcard or ucc", wildcard_or_ucc_certificates_url)
-
else
-
crumb << link_to("single domain", single_domain_certificates_url)
-
end
-
crumb << " :: #{@certificate.title}"
-
end
-
-
1
def new_certificate_params
-
if @certificate_order.is_unused_credit?
-
[@certificate_order, {:url=>:update_csr_certificate_order}]
-
# elsif @certificate.is_free?
-
# [@certificate_order, {url: :create_free_ssl}]
-
elsif current_user && current_user.ssl_account.is_registered_reseller?
-
@certificate_order
-
else
-
[@certificate_order, {:url=>:new_order}]
-
end
-
end
-
-
1
def buy_or_get
-
@certificate.is_free? ? "Get" : "Buy"
-
end
-
-
1
def pricing(certificate)
-
last_duration_pricing certificate
-
end
-
-
1
def last_duration_pricing(certificate)
-
years = certificate.last_duration.value.to_i/365
-
years = 1 unless years > 0
-
factor = certificate.is_ucc? ? 1 : 1
-
p = lambda do |certificate|
-
if certificate.is_ucc?
-
certificate.first_domains_tiers.last.price * 3
-
else
-
certificate.last_duration.price
-
end
-
end
-
price = p.call(certificate)
-
orig_price = p.call(certificate.untiered)
-
actual = (price/years).format
-
orig = (certificate.tiered? ?
-
(orig_price/years).format : nil) unless certificate.is_dv?
-
render :partial=>'pricing', :locals=>{:actual=>actual, :orig=>orig}
-
end
-
-
1
def first_duration_pricing
-
actual = certificate.first_duration.price.format
-
orig = (certificate.tiered? ?
-
certificate.untiered.first_duration.price.format : nil) unless
-
certificate.is_dv?
-
render :partial=>'pricing', :locals=>{:actual=>actual, :orig=>orig}
-
end
-
end
-
1
module ContactsHelper
-
1
def setup_certificate_contacts(certificate_content)
-
certificate_content.tap do |cc|
-
if cc.certificate_contacts.empty?
-
cc.billing_checkbox, cc.technical_checkbox, cc.validation_checkbox =
-
true, true, true
-
end
-
end
-
end
-
-
1
def render_contact_fields(c, role)
-
render '/contacts/certificate_contact', :f => c,
-
:contact_role=>role
-
end
-
-
1
def render_saved_registrants(list, with_data=nil)
-
list.inject([]) do |registrants, r|
-
main_info = {}
-
remove = %w{id notes type contactable_id contactable_type created_at updated_at}
-
final = r.attributes.merge('status' => r.status)
-
final.each {|key, val| main_info["#{with_data ? 'data-' : ''}#{key}"] = val}
-
main_info = main_info.delete_if {|k,v| remove.include?(k.remove 'data-')}
-
option = "#{r.company_name} (#{r.status ? r.status.humanize : 'N/A'})"
-
registrants << [option, r.id, main_info]
-
registrants.sort
-
end
-
end
-
-
1
def render_saved_contacts(list, with_data=nil)
-
list.inject([]) do |contacts, c|
-
main_info = {}
-
recipient = c.type == 'IndividualValidation'
-
full_name = "#{c.last_name}, #{c.first_name}"
-
company = c.company_name
-
remove = %w{id notes type contactable_id contactable_type created_at updated_at}
-
c.attributes.each do |key, val|
-
cur_val = (recipient && (key == 'status')) ? c.status : val
-
main_info["#{with_data ? 'data-' : ''}#{key}"] = cur_val
-
end
-
main_info = main_info.delete_if {|k,v| remove.include?(k.remove 'data-')}
-
option = if c.type == 'Registrant'
-
c.individual? ? "#{full_name} (individual)" : "#{company} (organization)"
-
elsif recipient
-
[full_name, c.email].join(' | ')
-
else
-
[full_name, company].join(' | ')
-
end
-
contacts << [option, c.id, main_info]
-
contacts.sort
-
end
-
end
-
end
-
1
module FundedAccountsHelper
-
-
# do we show the billing info prompt?
-
1
def initial_display?
-
return {} unless current_user
-
ssl = (@reprocess_ucc || @payable_invoice) ? @ssl_account : current_user.ssl_account
-
((ssl.billing_profiles(true).reject(&"expired?".to_sym).blank? && !current_page?(action: "allocate_funds")) ||
-
@funded_account.try(:funding_source)==FundedAccount::NEW_CREDIT_CARD ||
-
!@billing_profile.try(:errors).blank? || !flash.now[:error].blank?) ?
-
{} : {:class => 'hidden'}
-
end
-
-
1
def initial_reseller_deposit?
-
current_user.ssl_account.has_role?('new_reseller') && current_user.ssl_account.reseller && (
-
current_user.ssl_account.reseller.enter_billing_information? ||
-
current_user.ssl_account.reseller.select_tier?)
-
end
-
-
1
def load_amounts(deduct_order)
-
max_load_amount = Money.new(1000000)
-
min_load_amount = Money.new(100000)
-
step_amount = Money.new(300000)
-
order_amount = current_order.amount or step_amount
-
if order_amount.cents > max_load_amount.cents
-
[[order_amount.format(:with_currency), order_amount.cents.to_s]]
-
else
-
skip = (deduct_order)? order_amount.cents / step_amount.cents : 0
-
brackets = (max_load_amount.cents / step_amount.cents).enum_for(:times).collect{|x|
-
bracket_amount = Money.new((x+1)*(step_amount.cents))
-
[bracket_amount.format(:with_currency=>true), bracket_amount.to_s]}
-
while skip > 0
-
brackets.shift
-
skip-=1
-
end
-
brackets.find_all{|x|x[1].to_f >= min_load_amount.to_s.to_f}
-
end
-
end
-
-
1
def funded_account_balance(with_currency=nil)
-
account = current_user.ssl_account.funded_account(true)
-
if with_currency == :with_currency
-
(account.nil? or account.amount.to_s == "0.00") ?
-
"$0.00 USD" : account.amount.format(:with_currency => true)
-
else
-
(account.nil?) ? "0.00" : account.amount
-
end
-
end
-
-
1
def destroy_credit_card_link(item, options={})
-
link_to 'delete', billing_profile_path(id: item), :remote=>true,
-
:class=>'delete_profile', :method => :delete, id: options[:id],
-
:confirm => "Are you sure you want to delete the credit card profile for #{item.masked_card_number}? This action cannot be undone."
-
end
-
-
1
def apply_or_free
-
is_order_free? ? create_free_ssl_path : apply_funds_path
-
end
-
end
-
1
module LayoutsHelper
-
1
def is_on?(model,current_slug={})
-
current_page?(eval("#{model}_path(#{current_slug})")) ||
-
(current_page?(eval("search_#{model}_path(#{current_slug})")) if Rails.application.routes.url_helpers.respond_to?("search_#{model}_path"))
-
end
-
end
-
1
module OrdersHelper
-
-
1
def stats(unpaginated)
-
if current_user.is_admin?
-
# Invoiced orders
-
invoice_items = unpaginated.where(state: 'invoiced')
-
-
@payable_invoices = Invoice
-
.where.not(billable_id: nil, type: nil)
-
.where(id: invoice_items.pluck(:invoice_id).uniq).joins(:orders).includes(:orders)
-
-
@pending_payable_invoices = @payable_invoices
-
.where(status: 'pending')
-
.where(orders: {approval: 'approved'})
-
.map(&:orders).flatten.uniq
-
.select{|o| invoice_items.include?(o)}.sum(&:cents)
-
-
@paid_payable_invoices = @payable_invoices
-
.where(status: ['paid', 'partially_refunded'])
-
.where(orders: {approval: 'approved'})
-
.map(&:orders).flatten.uniq
-
.select{|o| invoice_items.include?(o)}.sum(&:cents)
-
-
@refunded_payable_invoices = @payable_invoices
-
.where(status: 'refunded')
-
.where(orders: {approval: 'approved'})
-
.map(&:orders).flatten.uniq
-
.select{|o| invoice_items.include?(o)}.sum(&:cents)
-
-
@partial_refunds_payable_invoices = @payable_invoices
-
.where(status: 'partially_refunded')
-
.where(orders: {approval: 'approved'})
-
.map(&:payment).map(&:refunds).flatten.uniq.sum(&:amount)
-
-
@paid_payable_invoices -= @partial_refunds_payable_invoices
-
-
@payable_invoices_count = @payable_invoices.uniq.count
-
@invoiced_orders_count = invoice_items.count
-
-
# Non invoiced orders
-
@negative = unpaginated
-
.where(state: %w{charged_back canceled rejected payment_not_required payment_declined})
-
.where.not(description: [Order::MI_PAYMENT, Order::DI_PAYMENT]) # exclude invoice payments (as order)
-
.where.not(state: 'invoiced') # exclude invoice items (as order)
-
.sum(:cents)
-
-
refunded = Refund.where(
-
order_id: unpaginated
-
.where.not(description: [Order::MI_PAYMENT, Order::DI_PAYMENT])
-
.where.not(state: 'invoiced')
-
.where(state: ['partially_refunded', 'fully_refunded']).map(&:id)
-
).where(status: 'success')
-
-
deposits = unpaginated.joins{ line_items.sellable(Deposit) }
-
-
orders = unpaginated.where.not(id: deposits.map(&:id))
-
.where.not(description: [Order::MI_PAYMENT, Order::DI_PAYMENT])
-
.where.not(state: 'invoiced')
-
-
# Funded Account Withdrawal
-
faw = unpaginated.where(description: Order::FAW).sum(:cents)
-
-
deposits = deposits.where.not(description: Order::FAW)
-
-
@refunded_amount = refunded.sum(:amount)
-
@refunded_count = refunded.count
-
@deposits_amount = deposits.sum(:cents)
-
@deposits_count = deposits.count
-
@total_amount = orders.sum(:cents) - @negative - @refunded_amount - faw
-
@total_count = orders.count
-
end
-
end
-
-
1
def cart_items
-
if current_user && current_user.ssl_account.has_role?('new_reseller') && current_user.ssl_account.reseller
-
return [current_user.ssl_account.reseller.reseller_tier]
-
elsif !@certificate_order.blank?
-
return [@certificate_order]
-
elsif !@certificate_orders.blank?
-
certs=[]
-
@certificate_orders.each do |cert|
-
cert.quantity.times do
-
certs<<cert
-
end
-
end
-
return certs
-
elsif @funded_account
-
return []
-
end
-
[] #use cart_products if products expand beyond certs
-
end
-
-
1
def cart_items_count
-
items=cart_contents.reject{|c|c and c[ShoppingCart::PRODUCT_CODE]=~/\Areseller_tier/}
-
current_user ? items.select{|i|current_user.ssl_account.can_buy?(i)}.count : items.count
-
end
-
-
1
def current_order
-
order = current_user.nil? ? User.new.ssl_accounts.build.purchase(*cart_items) :
-
current_user.ssl_account.purchase(*cart_items)
-
order.cents = cart_items.inject(0){|result, element| result +
-
element.attributes_before_type_cast["amount"].to_f}
-
order
-
end
-
-
1
def domains_adjustment_order
-
if current_user
-
amount = Money.new(params[:order_amount].to_f * 100)
-
@ssl_account = @certificate_order.ssl_account
-
order = @ssl_account.purchase(@certificate_order)
-
order.amount = amount
-
order.cents = amount.cents
-
order.invoice_description = params[:order_description]
-
order
-
end
-
end
-
-
1
def current_order_reprocess_ucc
-
if current_user
-
@ssl_account = @certificate_order.ssl_account
-
order = @ssl_account.purchase(@certificate_order)
-
order.cents = @certificate_order.ucc_prorated_amount(@certificate_content, @tier)
-
order.amount = Money.new(order.cents)
-
order.type = "ReprocessCertificateOrder"
-
order
-
end
-
end
-
-
1
def is_current_order_affordable?
-
current_user.ssl_account.funded_account.amount.cents >=
-
current_order.amount.cents
-
end
-
-
1
def cart_total_price
-
Money.new(cart_items.sum(&:amount)).format :with_currency => true
-
end
-
-
1
def min_cart_item_price
-
Money.new(cart_items.minimum(&:amount)).format :with_currency => true
-
end
-
-
1
def max_cart_item_price
-
Money.new(cart_items.maximum(&:amount)).format :with_currency => true
-
end
-
-
1
def avg_cart_item_price
-
Money.new(cart_items.average(&:amount)).format :with_currency => true
-
end
-
-
1
def link_to_checkout
-
if cart_items.size > 0 and logged_in? and !current_user.funded_account.blank? and (current_user.funded_account.amount.cents >= current_order.amount.cents)
-
link_to "Checkout", confirm_funds_path
-
elsif cart_items.size > 0
-
link_to "Checkout", allocate_funds_for_order_path
-
end
-
end
-
-
1
def apply_order
-
(@order.cents > 0 or @order.is_free?) and @funded_account.deduct_order?
-
end
-
-
1
def display_line_items(order, formatted=true)
-
content_tag("div", order.line_items.inject("") {|str, line_item|
-
str << content_tag("div", "#{line_item.sellable.class.to_s} -
-
#{line_item.sellable.description.shorten(20,false)}",
-
:class => "line_item_receipt")}, :class=> "line_items_receipt")
-
end
-
-
1
def is_cart_empty?
-
cart_items.size==0
-
end
-
-
1
def new_order_title(certificate=nil)
-
"Checkout #{' And Subscriber Agreement' if certificate}"
-
end
-
-
1
def ssl_account
-
current_user.try(:ssl_account)
-
end
-
-
1
def reseller_initial_deposit?
-
return false if ssl_account.reseller.blank?
-
ssl_account.reseller.enter_billing_information? || ssl_account.reseller.select_tier?
-
end
-
-
1
def reseller_tier_is_free?
-
ssl_account.reseller.reseller_tier.try(:amount) <=0
-
end
-
-
1
def is_receipt?
-
(@deposit && @deposit.receipt) || (@order && @order.receipt)
-
end
-
-
1
def determine_eligibility_to_buy(certificate, certificate_order)
-
unless current_user.blank?
-
current_user.ssl_account.clear_new_certificate_orders
-
unless current_user.ssl_account.can_buy?(certificate)
-
flash.now[:error] = "Certificate belongs to a pricing tier which differs
-
from your reseller tier level"
-
return render(:template => "/certificates/buy", :layout=>"application")
-
else
-
certificate_order.ssl_account = current_user.ssl_account
-
end
-
end
-
end
-
-
1
def url_to_new_order
-
url = @certificate_orders ? create_multi_free_ssl_orders_path : create_free_ssl_orders_path
-
[Order.new]+ (is_order_free? ? [{url: url}] : [])
-
end
-
-
1
def is_order_free?
-
current_order.amount.to_s.to_i<=0
-
end
-
-
1
def confirm_affiliate_sale
-
# @order.reload
-
if !@order.domains_adjustment? && !@order.invoice_payment? && !@order.on_payable_invoice?
-
!@order.ext_affiliate_credited? && (@order.persisted? ? @order.created_at > 1.minute.ago : true )
-
@order.toggle! :ext_affiliate_credited
-
if @order.ext_affiliate_name=="shareasale"
-
"<img src=\"https://shareasale.com/sale.cfm?amount=#{@order.final_amount.to_s}&tracking=#{@order.reference_number}&transtype=sale&merchantID=#{@order.ext_affiliate_id}\" width=\"1\" height=\"1\">".html_safe
-
else
-
"<img border=\"0\" src=\"https://#{Settings.community_domain}/affiliate/sale.php?profile=#{@order.ext_affiliate_id}&idev_saleamt=#{@order.final_amount.to_s}&idev_ordernum=#{@order.reference_number}#{"&coupon_code="+@order.discounts.last.ref unless @order.discounts.empty?}\" width=\"1\" height=\"1\">".html_safe
-
end if @order.amount.cents > 0
-
end
-
end
-
-
1
def row_description(order)
-
if order.is_a?(CertificateOrder)
-
order.respond_to?(:description_with_tier) ? order.description_with_tier(@order) :
-
certificate_type(order)
-
elsif order.is_a?(ProductOrder)
-
order.product.title
-
else
-
order.class.name
-
end
-
end
-
-
1
def log_declined_transaction(transaction, last_four)
-
unless current_user.nil?
-
fa = current_user.ssl_account.funded_account
-
declined = fa.card_recently_declined?
-
cards = declined ? fa.card_declined[:cards] : []
-
fa.update(card_declined: nil) unless declined
-
if transaction && transaction.message.include?('This transaction has been declined')
-
fa.update(
-
card_declined: {
-
order_transaction_id: transaction.try(:id),
-
user_id: current_user.try(:id),
-
cards: cards.push(last_four),
-
declined_at: DateTime.now,
-
controller: "#{controller_name}##{action_name}",
-
}
-
)
-
fa.delay_transaction
-
end
-
end
-
end
-
-
1
def test_label(order)
-
unless order.display_state.blank?
-
order.display_state+" "
-
else
-
order.is_test? ? "(TEST) " : ""
-
end
-
end
-
-
1
def delay_transaction?
-
fa = current_user.ssl_account.funded_account if current_user
-
declined = fa && fa.card_recently_declined? if fa
-
next_try = fa.card_declined[:next_attempt] if declined
-
cards = fa.card_declined[:cards] if declined
-
return false if !declined || (declined && cards && cards.any? && cards.count < 2)
-
declined && next_try && (next_try > DateTime.now)
-
end
-
-
1
def order_invoice_notes
-
"Payment for #{@invoice.get_type_format.downcase} invoice total of #{@invoice.get_amount_format} due on #{@invoice.end_date.strftime('%F')}."
-
end
-
-
1
def ucc_csr_submit_notes
-
"Initial CSR submit, UCC domains adjustment (certificate order: #{@certificate_order.ref}, certificate content: #{@certificate_content.ref})"
-
end
-
-
1
def renew_ucc_notes
-
"Renewal UCC domains adjustment (certificate order: #{@certificate_order.ref}, certificate content: #{@certificate_content.ref})"
-
end
-
-
1
def reprocess_ucc_notes
-
"Reprocess UCC (certificate order: #{@certificate_order.ref}, certificate content: #{@certificate_content.ref})"
-
end
-
-
1
def smime_client_enrollment_notes(emails_count=nil)
-
"S/MIME or Client enrollment for #{emails_count} emails."
-
end
-
-
1
def ucc_or_invoice_params
-
order = params[:order] || params[:smime_client_enrollment_order]
-
-
unless @payable_invoice
-
@ssl_account = if current_user.is_system_admins?
-
CertificateOrder.find_by(ref: params[:order][:co_ref]).ssl_account
-
else
-
current_user.ssl_account
-
end
-
end
-
-
unless params[:funding_source].nil? ||
-
(params[:funding_source] && params[:funding_source] == 'paypal')
-
existing_card = @ssl_account.billing_profiles.find(params[:funding_source])
-
end
-
-
@funded_amount = order[:funded_amount].to_f
-
@order_amount = order[:order_amount].to_f
-
@charge_amount = order[:charge_amount].to_f
-
@too_many_declines = delay_transaction? && (params[:payment_method] == 'credit_card')
-
@billing_profile = BillingProfile.new(params[:billing_profile]) if params[:billing_profile]
-
@profile = existing_card || @billing_profile
-
@credit_card = @profile.build_credit_card
-
@funded_account_init = @ssl_account.funded_account.cents
-
@target_amount = (@charge_amount.blank? || @charge_amount == 0) ? @order_amount : @charge_amount
-
-
if @reprocess_ucc || @renew_ucc || @ucc_csr_submit
-
@certificate_order = @ssl_account.cached_certificate_orders.find_by(ref: order[:co_ref])
-
@certificate_content = @certificate_order.certificate_contents.find_by(ref: order[:cc_ref])
-
end
-
end
-
-
1
def withdraw_funded_account(credit_amount, full_amount=0)
-
@order.save unless @order.persisted?
-
order_amount = @order_amount || full_amount
-
fully_covered = credit_amount >= (order_amount * 100).to_i
-
full_amount = fully_covered ? @order.amount.format : Money.new(@order.cents + credit_amount).format
-
notes = "#{fully_covered ? 'Full' : 'Partial'} payment for order ##{@order.reference_number} (#{full_amount}) "
-
notes << "for UCC certificate reprocess." if @reprocess_ucc
-
notes << "for renewal UCC domains adjustment." if @renew_ucc
-
notes << "for initial CSR submit UCC domains adjustment." if @ucc_csr_submit
-
notes << "for #{@invoice.get_type_format.downcase} invoice ##{@invoice.reference_number}." if @payable_invoice
-
-
fund = Deposit.create(
-
amount: credit_amount,
-
full_name: "Team #{@ssl_account.get_team_name} funded account",
-
credit_card: 'N/A',
-
last_digits: 'N/A',
-
payment_method: 'Funded Account'
-
)
-
-
@funded = @ssl_account.purchase fund
-
@funded.description = 'Funded Account Withdrawal'
-
@funded.notes = notes
-
@funded.save
-
@funded.mark_paid!
-
@ssl_account.funded_account.decrement! :cents, credit_amount
-
@ssl_account.funded_account.save
-
end
-
-
1
def get_order_notes
-
return reprocess_ucc_notes if @reprocess_ucc
-
return order_invoice_notes if @payable_invoice
-
return renew_ucc_notes if @renew_ucc
-
return ucc_csr_submit_notes if @ucc_csr_submit
-
return smime_client_enrollment_notes('') if @order.is_a?SmimeClientEnrollmentOrder
-
''
-
end
-
-
1
def get_order_descriptions
-
return Order::DOMAINS_ADJUSTMENT if @reprocess_ucc || @renew_ucc || @ucc_csr_submit
-
return (@ssl_account.get_invoice_pmt_description) if @payable_invoice
-
return Order::S_OR_C_ENROLLMENT if @order.is_a?SmimeClientEnrollmentOrder
-
Order::SSL_CERTIFICATE
-
end
-
-
1
def ucc_update_domain_counts
-
co = @certificate_order
-
notes = []
-
order = params[:order]
-
reseller_tier = @tier || find_tier
-
-
# domains entered
-
wildcard = order ? order[:wildcard_count].to_i : params[:wildcard_count].to_i
-
nonwildcard = order ? order[:nonwildcard_count].to_i : params[:nonwildcard_count].to_i
-
-
# max domain counts stored
-
co_nonwildcard = co.nonwildcard_count.blank? ? 0 : co.nonwildcard_count
-
co_wildcard = co.wildcard_count.blank? ? 0 : co.wildcard_count
-
-
# max for previous signed certificates to determine credited domains
-
prev_wildcard = co.get_reprocess_max_wildcard(co.certificate_content).count
-
prev_nonwildcard = co.get_reprocess_max_nonwildcard(co.certificate_content).count
-
-
if (co_nonwildcard > prev_nonwildcard) &&
-
((nonwildcard > co_nonwildcard) || (@reprocess_ucc &&
-
(nonwildcard >= co_nonwildcard && (nonwildcard > 0))))
-
notes << "#{co_nonwildcard - prev_nonwildcard} non wildcard domains"
-
end
-
-
if (co_wildcard > prev_wildcard) &&
-
((wildcard > co_wildcard) || (@reprocess_ucc &&
-
(wildcard >= co_wildcard && (wildcard > 0))))
-
notes << "#{co_wildcard - prev_wildcard} wildcard domains"
-
end
-
-
# record new max counts
-
new_nonwildcard = nonwildcard > co_nonwildcard ? nonwildcard : co_nonwildcard
-
new_wildcard = wildcard > co_wildcard ? wildcard : co_wildcard
-
co.update( nonwildcard_count: new_nonwildcard, wildcard_count: new_wildcard )
-
@order.max_non_wildcard = new_nonwildcard
-
@order.max_wildcard = new_wildcard
-
-
if reseller_tier
-
@order.reseller_tier_id = ResellerTier.find_by(label: find_tier.delete('tr')).try(:id)
-
end
-
-
if notes.any?
-
@order.invoice_description = '' if @order.invoice_description.nil?
-
@order.invoice_description << " Received credit for #{notes.join(' and ')}."
-
end
-
@order.lock!
-
@order.save
-
end
-
-
1
def purchase_successful?
-
return false unless (ActiveMerchant::Billing::Base.mode == :test ? true : @credit_card.valid?)
-
-
@order.description = get_order_descriptions
-
-
other_order = @reprocess_ucc || @renew_ucc || @payable_invoice
-
-
options = @profile.build_info(@order.description.gsub('Payment', 'Pmt')).merge(
-
stripe_card_token: params[:billing_profile][:stripe_card_token],
-
owner_email: current_user.nil? ? params[:user][:email] : current_user.ssl_account.get_account_owner.email
-
)
-
options.merge!(amount: (@target_amount.to_f * 100).to_i) if other_order
-
-
@gateway_response = @order.purchase(@credit_card, options)
-
log_declined_transaction(@gateway_response, @credit_card.number.last(4)) unless @gateway_response.success?
-
(@gateway_response.success?).tap do |success|
-
if success
-
flash.now[:notice] = @gateway_response.message
-
@order.mark_paid!
-
# in case the discount becomes invalid before check out, give it to the customer
-
unless other_order
-
@order.discounts.each do |discount|
-
Discount.decrement_counter(:remaining, discount) unless discount.remaining.blank?
-
end
-
end
-
SystemAudit.create(
-
owner: current_user,
-
target: @order,
-
action: "purchase successful",
-
notes: get_order_notes
-
)
-
elsif @order.invoiced?
-
flash[:notice] = "Order has been added to invoice due to transaction failure. #{@gateway_response.message}"
-
SystemAudit.create(
-
owner: current_user,
-
target: @order,
-
action: "order added to invoice due to denied transaction",
-
notes: @gateway_response.message
-
)
-
return true
-
else
-
flash.now[:error] = if @gateway_response.message=~/no match/i
-
"CVV code does not match"
-
else
-
@gateway_response.message #no descriptive enough
-
end
-
@order.transaction_declined!
-
unless other_order
-
@certificate_order.destroy unless @certificate_order.blank?
-
end
-
end
-
end
-
end
-
-
1
def order_reqs_valid?
-
@order.valid? && (params[:funding_source] ? @profile.valid? :
-
@billing_profile.valid?) && (current_user || @user.valid?)
-
end
-
-
# ============================================================================
-
# S/MIME OR CLIENT ENROLLMENT ORDER
-
# ============================================================================
-
1
def smime_client_parse_emails(emails=nil)
-
emails_list = emails || params[:emails]
-
if emails_list.is_a? Array
-
@emails = emails_list
-
else
-
unless emails_list.strip.blank?
-
@emails = emails_list
-
.strip.split(/[\s,]+/).map(&:strip).map(&:downcase)
-
@emails.select {|e| e =~ URI::MailTo::EMAIL_REGEXP}
-
end
-
end
-
end
-
-
1
def smime_client_enrollment_co_paid
-
@order.cached_certificate_orders.update_all(
-
ssl_account_id: @ssl_account.try(:id), workflow_state: 'paid'
-
)
-
end
-
-
1
def smime_client_enrollment_registrants
-
registrant_params = @ssl_account.epki_registrant.attributes
-
.except(*%w{id created_at updated_at type domains roles})
-
.merge({
-
'parent_id' => @ssl_account.epki_registrant.id,
-
'status' => Contact::statuses[:validated]
-
})
-
ccs = CertificateContent.joins(certificate_order: :orders)
-
.where(orders: {id: @order.id})
-
ccs.each do |cc|
-
cc.create_registrant(registrant_params)
-
cc.create_locked_registrant(registrant_params)
-
cc.save
-
end
-
end
-
-
1
def smime_client_enrollment_validate
-
if current_user && @order && @order.persisted?
-
@order.smime_client_enrollment_validate(current_user.id)
-
end
-
end
-
-
1
def smime_client_enrollment_items
-
if @certificate
-
@emails.inject([]) do |cos, email|
-
co = CertificateOrder.new(
-
has_csr: false, ssl_account: @ssl_account, duration: params[:duration]
-
)
-
co.certificate_contents << CertificateContent.new(domains: [email])
-
cos << Order.setup_certificate_order(
-
certificate: @certificate, certificate_order: co
-
)
-
cos
-
end
-
else
-
[]
-
end
-
end
-
-
=begin
-
def setup_certificate_order
-
#adjusting duration to reflect number of days validity
-
duration = @certificate_order.duration.to_i * 365
-
@certificate_order.certificate_contents[0].duration = duration
-
if @certificate.is_ucc? || @certificate.is_wildcard?
-
psl = @certificate.items_by_server_licenses.find{|item|
-
item.value==duration.to_s}
-
so = SubOrderItem.new(:product_variant_item=>psl,
-
:quantity=>@certificate_order.server_licenses.to_i,
-
:amount=>psl.amount*@certificate_order.server_licenses.to_i)
-
@certificate_order.sub_order_items << so
-
if @certificate.is_ucc?
-
pd = @certificate.items_by_domains.find_all{|item|
-
item.value==duration.to_s}
-
additional_domains = (@certificate_order.certificate_contents[0].
-
domains.try(:size) || 0) - Certificate::UCC_INITIAL_DOMAINS_BLOCK
-
so = SubOrderItem.new(:product_variant_item=>pd[0],
-
:quantity=>Certificate::UCC_INITIAL_DOMAINS_BLOCK,
-
:amount=>pd[0].amount*Certificate::UCC_INITIAL_DOMAINS_BLOCK)
-
@certificate_order.sub_order_items << so
-
if additional_domains > 0
-
so = SubOrderItem.new(:product_variant_item=>pd[1],
-
:quantity=>additional_domains,
-
:amount=>pd[1].amount*additional_domains)
-
@certificate_order.sub_order_items << so
-
end
-
end
-
end
-
unless @certificate.is_ucc?
-
pvi = @certificate.items_by_duration.find{|item|item.value==duration.to_s}
-
so = SubOrderItem.new(:product_variant_item=>pvi, :quantity=>1,
-
:amount=>pvi.amount)
-
@certificate_order.sub_order_items << so
-
end
-
@certificate_order.amount = @certificate_order.sub_order_items.map(&:amount).sum
-
@certificate_order.certificate_contents[0].
-
certificate_order = @certificate_order
-
end
-
=end
-
end
-
1
module OtherPartyValidationRequestsHelper
-
end
-
1
module PasswordResetsHelper
-
end
-
1
module PaypalExpressHelper
-
1
def get_setup_purchase_params(cart, request, params)
-
@subtotal, @shipping, @total = get_totals(cart, params)
-
@items = get_items(cart)
-
credit_and_discount params
-
load_funds(params) unless params[:reprocess_ucc] || params[:monthly_invoice]
-
-
@return_url_params = {
-
action: 'purchase',
-
ssl_slug: params[:ssl_slug],
-
only_path: false,
-
deduct_order: params[:deduct_order],
-
order_description: params[:order_description]
-
}
-
-
get_domains_adjustments
-
-
if params[:monthly_invoice]
-
@return_url_params.merge!({
-
invoice_ref: params[:invoice_ref],
-
monthly_invoice: true
-
})
-
end
-
-
if params[:smime_client_order]
-
@return_url_params.merge!({
-
certificate: params[:certificate],
-
emails: params[:emails],
-
smime_client_order: true
-
})
-
end
-
-
return to_cents(@total), {
-
ip: request.remote_ip,
-
return_url: url_for(@return_url_params),
-
cancel_return_url: root_url,
-
subtotal: to_cents(@total),
-
shipping: to_cents(@shipping),
-
handling: 0,
-
tax: 0,
-
allow_note: true,
-
items: @items,
-
}
-
end
-
-
1
def get_domains_adjustments
-
if params[:reprocess_ucc] || params[:renew_ucc] || params[:ucc_csr_submit]
-
dom_params = {
-
co_ref: params[:co_ref],
-
cc_ref: params[:cc_ref],
-
wildcard_amount: params[:wildcard_amount],
-
nonwildcard_amount: params[:nonwildcard_amount],
-
wildcard_count: params[:wildcard_count],
-
nonwildcard_count: params[:nonwildcard_count]
-
}
-
dom_params.merge!(reprocess_ucc: true) if params[:reprocess_ucc]
-
dom_params.merge!(renew_ucc: true) if params[:renew_ucc]
-
dom_params.merge!(ucc_csr_submit: true) if params[:ucc_csr_submit]
-
@return_url_params.merge!(dom_params)
-
end
-
end
-
-
1
def get_order_info(gateway_response, cart)
-
subtotal, shipping, total = get_totals(cart)
-
{
-
shipping_address: gateway_response.address,
-
email: gateway_response.email,
-
name: gateway_response.name,
-
gateway_details: {
-
:token => gateway_response.token,
-
:payer_id => gateway_response.payer_id,
-
},
-
subtotal: gateway_response.params['order_total'],
-
shipping: gateway_response.params['shipping_total'],
-
total: gateway_response.params['order_total']
-
}
-
end
-
-
1
def get_shipping(cart)
-
# define your own shipping rule based on your cart here
-
# this method should return an integer
-
end
-
-
1
def get_items(cart)
-
if params[:reprocess_ucc]
-
[{
-
name: "Reprocess UCC Cert",
-
number: "reprocess order",
-
quantity: 1,
-
amount: get_amount(params[:amount])
-
}]
-
elsif params[:monthly_invoice]
-
[{
-
name: "Monthly Invoice Pmt",
-
number: "payment",
-
quantity: 1,
-
amount: get_amount(params[:amount])
-
}]
-
elsif params[:renew_ucc]
-
[{
-
name: "Renew UCC Cert",
-
number: "renewal order",
-
quantity: 1,
-
amount: get_amount(params[:amount])
-
}]
-
elsif params[:ucc_csr_submit]
-
[{
-
name: "UCC Cert Adjustment",
-
number: "adjustment order",
-
quantity: 1,
-
amount: get_amount(params[:amount])
-
}]
-
elsif params[:smime_client_order]
-
[{
-
name: "S/MIME Client Enroll",
-
number: "enrollment order",
-
quantity: 1,
-
amount: get_amount(params[:amount])
-
}]
-
else
-
cart.line_items.collect do |line_item|
-
if line_item.sellable.is_a?(Deposit)
-
{
-
:name => "Deposit",
-
:number => "sslcomdeposit"
-
}
-
elsif line_item.sellable.is_a?(ResellerTier)
-
product = line_item.sellable
-
{
-
:name => product.roles,
-
:number => product.roles
-
}
-
else
-
product = line_item.sellable.is_a?(CertificateOrder) ? line_item.sellable.certificate : line_item.sellable
-
{
-
:name => product.title,
-
:number => product.serial
-
}
-
end.merge(quantity: 1, amount: line_item.amount.cents )
-
end
-
end
-
end
-
-
1
def get_purchase_params(gateway_response, request, params)
-
items = gateway_response.params['PaymentDetails']['PaymentDetailsItem']
-
items=[items] unless items.is_a?(Array)
-
new_items = items.map{|i|
-
{amount: to_cents(i['Amount'].to_f * 100),
-
name: i['Name'],
-
quantity: i['Quantity'],
-
Number: i['Number']}
-
}
-
return to_cents(gateway_response.params['order_total'].to_f * 100), {
-
:ip => request.remote_ip,
-
:token => gateway_response.token,
-
:payer_id => gateway_response.payer_id,
-
:subtotal => to_cents(gateway_response.params['order_total'].to_f * 100),
-
:shipping => to_cents(gateway_response.params['shipping_total'].to_f * 100),
-
:handling => 0,
-
:tax => 0,
-
:items => new_items
-
}
-
end
-
-
1
def get_totals(cart, params)
-
subtotal = if params[:reprocess_ucc] || params[:monthly_invoice] || params[:smime_client_order]
-
get_amount(params[:amount])
-
else
-
cart.amount.cents
-
end
-
discount = get_amount(params[:discount])
-
credit = get_amount(params[:funded_account])
-
surplus = get_surplus_deposit(params) > 0 ? get_surplus_deposit(params) : 0
-
shipping = 0.0
-
total = (subtotal - credit - discount) + surplus + shipping
-
return subtotal, shipping, total
-
end
-
-
1
def to_cents(money)
-
(money*1).round
-
end
-
-
1
def credit_and_discount(params)
-
funded_account_amt = get_amount(params[:funded_account])
-
discount_amt = get_amount(params[:discount])
-
-
if params[:discount_code] && (discount_amt > 0)
-
@items.push({
-
name: 'Discount',
-
number: params[:discount_code],
-
quantity: 1,
-
amount: -discount_amt
-
})
-
end
-
# add credit from funded account towards purchase
-
if params[:funded_account] && (funded_account_amt > 0)
-
@items.push({
-
name: 'Funded Account',
-
number: 'Credit',
-
quantity: 1,
-
amount: -funded_account_amt
-
})
-
end
-
end
-
-
1
def load_funds(params)
-
# load additional (any amount above the purchase amount) to funded account
-
if params[:funded_target] && (get_surplus_deposit(params) > 0)
-
@items.push({
-
name: 'Load Funds',
-
number: 'to Funded Account',
-
quantity: 1,
-
amount: get_surplus_deposit(params)
-
})
-
end
-
end
-
-
1
def get_surplus_deposit(params)
-
special_order = params[:monthly_invoice] || params[:reprocess_ucc] || params[:smime_client_order]
-
funded = params[:funded_target]
-
final_total = params[:amount].to_i - get_amount(params[:discount]) - get_amount(params[:funded_account])
-
(funded && !special_order) ? get_amount(funded) - final_total : 0
-
end
-
-
1
def get_amount(amount=nil)
-
amount ? (amount.to_f * 100).round : 0
-
end
-
end
-
1
module ResellerTiersHelper
-
end
-
1
module RestfulApiHelper
-
end
-
1
module SignedCertificateHelper
-
1
def issuer_items(issuer)
-
results = []
-
items = issuer.split(',')
-
-
items.each do |item|
-
key = item.split('=')[0]
-
value = item.split('=')[1]
-
-
if key == 'CN'
-
results << ('Common Name (CN) : ' + value)
-
elsif key == 'OU'
-
results << ('Organization Unit (OU) : ' + value)
-
elsif key == 'O'
-
results << ('Organization (O) : ' + value)
-
elsif key == 'C'
-
results << ('Country (C) : ' + value)
-
end
-
end
-
-
results
-
end
-
end
-
1
module SiteChecksHelper
-
end
-
1
module SiteSealsHelper
-
1
def site_seal_status(site_seal)
-
case site_seal.workflow_state
-
when "new"
-
[SiteSeal::NEW_STATUS, 'attention']
-
when SiteSeal::FULLY_ACTIVATED.to_s
-
[SiteSeal::FULLY_ACTIVATED_STATUS, 'approved']
-
when SiteSeal::CONDITIONALLY_ACTIVATED.to_s
-
[SiteSeal::CONDITIONALLY_ACTIVATED_STATUS, 'pending']
-
when SiteSeal::DEACTIVATED.to_s
-
[SiteSeal::DEACTIVATED_STATUS, 'attention']
-
when SiteSeal::CANCELED.to_s
-
[SiteSeal::CANCELED_STATUS, 'attention']
-
else
-
['','']
-
end
-
end
-
-
1
def friendly_seal_type(seal_type)
-
case seal_type
-
when 'ev'
-
'extended validation premium'
-
when 'ov'
-
'high assurance standard'
-
when 'dv'
-
'basic'
-
end
-
end
-
-
1
def certificate_status(co, is_managing=nil)
-
pending = is_managing ? "pending" : "warning"
-
cc=co.certificate_content
-
case cc.workflow_state
-
when "issued"
-
if cc.csr.signed_certificate.blank?
-
["certificate missing", "attention"]
-
else
-
ef, ex = [cc.csr.signed_certificate.effective_date, cc.csr.
-
signed_certificate.expiration_date]
-
if ex.blank? || ef.blank?
-
#these were signed certs transferred over and somehow were missing these dates
-
["invalid certificate", "attention"]
-
elsif ex < Time.now
-
["invalid (expired on #{ex.strftime("%b %d, %Y")})", pending]
-
elsif ef > Time.now
-
["invalid (starts on #{ef.strftime("%b %d, %Y")})", pending]
-
else
-
["valid (#{ef.strftime("%b %d, %Y")} - #{ex.strftime("%b %d, %Y")})",
-
"approved"]
-
end
-
end
-
when "canceled"
-
["canceled", "attention"]
-
when "revoked"
-
["revoked", "attention"]
-
else
-
["pending issuance", pending]
-
end
-
end
-
-
1
def popup_code(co)
-
{style: "border: none;", onclick:
-
"window.open('#{site_report_site_seal_url(@ssl_slug, co.site_seal)}', 'site_report','#{co.validation_histories.blank? ?
-
SiteSeal::REPORT_DIMENSIONS : SiteSeal::REPORT_ARTIFACTS_DIMENSIONS}'); return false;",
-
onmouseover: "this.style.cursor='pointer'"}
-
end
-
end
-
1
module SslAccountsHelper
-
1
def cert_recipients_errors
-
"".tap do |result|
-
result << 'fieldWithErrors' unless @ssl_account.errors.
-
get(:preferred_processed_certificate_recipients).blank?
-
end
-
end
-
1
def reminder_emails_errors
-
"".tap do |result|
-
result << 'fieldWithErrors' unless @ssl_account.errors.
-
get(:preferred_reminder_notice_destinations).blank?
-
end
-
end
-
1
def receipt_emails_errors
-
"".tap do |result|
-
result << 'fieldWithErrors' unless @ssl_account.errors.
-
get(:preferred_receipt_recipients).blank?
-
end
-
end
-
1
def confirmation_emails_errors
-
"".tap do |result|
-
result << 'fieldWithErrors' unless @ssl_account.errors.
-
get(:preferred_confirmation_recipients).blank?
-
end
-
end
-
1
def reminder_trigger_errors(rnt)
-
"".tap do |result|
-
result << 'fieldWithErrors' unless SslAccount::TRIGGER_RANGE.
-
include?(rnt.to_i) && rnt=~/\d+/ || rnt.blank?
-
end
-
end
-
end
-
1
module UnsubscribesHelper
-
end
-
1
module UserSessionsHelper
-
end
-
1
module UsersHelper
-
1
def user_status(user)
-
result =
-
case user.status
-
when /suspended/, /canceled/
-
[$1, 'alert']
-
end
-
if result.blank?
-
result = (user.active?) ? ["activated", "good"] : ["not activated",
-
"caution"]
-
end
-
result
-
end
-
-
1
def ssl_account_status(user, account)
-
if user.ssl_accounts.include?(account)
-
params = {ssl_account_id: account.id}
-
ssl = user.ssl_account_users.where(params).first
-
if ssl && ssl.approved
-
['approved', 'good']
-
else
-
if user.user_declined_invite?(params)
-
['declined', 'caution']
-
elsif user.approval_token_valid?(params.merge(skip_match: true))
-
['sent', 'caution']
-
else
-
['token expired', 'caution']
-
end
-
end
-
end
-
end
-
-
1
def team_index_permissions(user, team)
-
permit = []
-
roles = user.role_symbols(team)
-
unless roles.empty?
-
roles.each do |role|
-
case role
-
when :users_manager
-
permit << [:users]
-
when :installer
-
permit << [:orders, :validations, :site_seals]
-
when :validations
-
permit << [:validations, :site_seals]
-
when :billing
-
permit << [:orders, :transactions, :billing_profiles]
-
when :account_admin, :owner, :reseller
-
permit << [:users, :orders, :transactions, :validations, :site_seals, :billing_profiles]
-
end
-
end
-
end
-
permit.flatten.uniq.compact
-
end
-
end
-
1
module ValidationsHelper
-
1
def overall_status(validation_rulings)
-
unless validation_rulings.empty?
-
dcvs=@cert_order.csr.domain_control_validations
-
last_sent=%w(http https).include?(dcvs.last.try(:dcv_method)) ? dcvs.last : dcvs.last_sent
-
dcv_wait=(!@cert_order.csr.blank? && last_sent.try("satisfied?")) ? "" :
-
", waiting for response to domain control validation email"
-
if validation_rulings.detect(&:new?)
-
unless @cert_order.is_express_signup?
-
[(@cert_order.certificate.is_ev? ? ValidationRuling::NEW_EV_STATUS : ValidationRuling::NEW_STATUS)+dcv_wait,
-
ValidationRuling::ATTENTION_CLASS]
-
else
-
[ValidationRuling::PENDING_EXPRESS_STATUS+dcv_wait, ValidationRuling::WAITING_CLASS]
-
end
-
elsif validation_rulings.detect(&:more_required?)
-
[ValidationRuling::MORE_REQUIRED_STATUS+dcv_wait, ValidationRuling::ATTENTION_CLASS]
-
elsif validation_rulings.detect(&:pending?)
-
[ValidationRuling::PENDING_STATUS+dcv_wait, ValidationRuling::WAITING_CLASS]
-
elsif validation_rulings.detect(&:unapproved?)
-
[ValidationRuling::UNAPPROVED_STATUS+dcv_wait, ValidationRuling::ATTENTION_CLASS]
-
elsif validation_rulings.all?(&:approved?)
-
[ValidationRuling::APPROVED_STATUS+dcv_wait, ValidationRuling::APPROVED_CLASS]
-
else
-
['','']
-
end
-
else
-
if @cert_order.migrated_from_v2?
-
#we need to depend on existence of csr and.or signed cert
-
if @cert_order.certificate_content.csr.blank?
-
["please submit certificate signing request (csr)", ValidationRuling::WAITING_CLASS]
-
elsif @cert_order.signed_certificate.blank?
-
["processing certificate", ValidationRuling::WAITING_CLASS]
-
else
-
['','']
-
end
-
else
-
cc = @cert_order.certificate_content
-
[certificate_order_status(cc,@cert_order),status_class(cc)]
-
end
-
end
-
end
-
-
1
def validation_status(validation_ruling)
-
if validation_ruling.new?
-
[ValidationRuling::WAITING_FOR_DOCS, ValidationRuling::ATTENTION_CLASS]
-
elsif validation_ruling.more_required?
-
[ValidationRuling::INSUFFICIENT, ValidationRuling::ATTENTION_CLASS]
-
elsif validation_ruling.pending?
-
[ValidationRuling::REVIEWING, ValidationRuling::WAITING_CLASS]
-
elsif validation_ruling.approved?
-
[ValidationRuling::APPROVED, ValidationRuling::APPROVED_CLASS]
-
elsif validation_ruling.unapproved?
-
[ValidationRuling::UNAPPROVED, ValidationRuling::ATTENTION_CLASS]
-
else
-
['','']
-
end
-
end
-
-
1
def satisfied(last_sent)
-
last_sent.satisfied? ? "dcv_satisfied" : "dcv_not_satisfied"
-
end
-
-
1
def last_sent(co)
-
return if co.csr.blank?
-
dcvs=co.csr.domain_control_validations
-
(%w(http https).include?(dcvs.last.try(:dcv_method))) ? dcvs.last : dcvs.last_sent
-
end
-
end
-
class DuplicateV2UserMailer < ActionMailer::Base
-
default :from => "SSL.com Certificate Services <no-reply@ssl.com>"
-
# default_url_options[:host] = Settings.community_domain
-
-
def duplicate_found(dup)
-
@to = @opvr.email_addresses.join(", ")
-
@technical_contact =
-
if @co.administrative_contact
-
[@co.administrative_contact.first_name, @co.administrative_contact.last_name].join(" ")
-
else
-
"An SSL.com customer"
-
end
-
subject = "Duplicate login info found for #{dup.model_and_id}"
-
mail(:to => @to, :subject => subject)
-
end
-
-
def attempted_login_by(dup)
-
@dup=dup
-
@to = Settings.notify_address
-
subject = "SSL.com System Notification: login attempt by duplicate login"
-
mail(:to => @to, :subject => subject)
-
end
-
-
def duplicates_found(dup, email_or_login)
-
@dup, @email_or_login=dup, email_or_login
-
@to = Settings.notify_address
-
subject = "SSL.com System Notification: attempted reset of user with duplicate #{email_or_login}"
-
mail(:to => @to, :subject => subject)
-
end
-
end
-
-
class OtherPartyRequestMailer < ActionMailer::Base
-
default :from => "SSL.com Certificate Services <support@ssl.com>"
-
# default_url_options[:host] = Settings.community_domain
-
-
def request_validation(other_party_validation_request)
-
@opvr = other_party_validation_request
-
@co = @opvr.other_party_requestable
-
@to = @opvr.email_addresses.join(", ")
-
@technical_contact =
-
if @co.administrative_contact
-
[@co.administrative_contact.first_name, @co.administrative_contact.last_name].join(" ")
-
else
-
"An SSL.com customer"
-
end
-
subject = "Validation Request for SSL.com Certificate #{@co.subject}"+(@opvr.preferred_show_order_number? ? " (Order Number #{@co.ref})" : "")
-
mail(:to => @to, :subject => subject)
-
end
-
end
-
-
class Reminder < ActionMailer::Base
-
default :from => "reminder@ssl.com", :bcc => ['info@ssl.com'], return_path: "reminder@ssl.com"
-
default_url_options[:host] = "ssl.com"
-
-
DO_NOT_SEND= %w(fiserv epsiia aturner@yisd.net cchavez@yisd.net gchavez@yisd.net ian@platinum.net d.riebeek@databaseonline.nl lsmith@patientplacement.com)
-
-
def expiring_notice(cert, contact)
-
prep(cert, contact)
-
subject = "SSL.com reminder - ssl certificate for #{@cert.common_name} expires in "+ time_ago_in_words(cert.expiration_date)
-
mail(:to => @to, :subject => subject)
-
end
-
-
def expired_notice(cert, contact)
-
prep(cert, contact)
-
subject = "SSL.com reminder - ssl certificate for #{@cert.common_name} expired "+ time_ago_in_words(cert.expiration_date) + " ago"
-
mail(:to => @to, :subject => subject)
-
end
-
-
def digest_notice(d)
-
preparing_recipients(d)
-
@e_certs = d[1].uniq
-
subject = "SSL.com reminder - ssl certificate expiration digest"
-
mail(:to => @to, :subject => subject)
-
end
-
-
def domain_digest_notice(d, result, notification_group)
-
preparing_recipients(d)
-
subject = "SSL.com notification group #{notification_group.friendly_name ||
-
notification_group.friendly_name.ref} scan for #{result.domain}"
-
@reminder_type = result.reminder_type
-
@result=result
-
@notification_group=notification_group
-
@ssl_slug=notification_group.ssl_account.to_slug if notification_group.ssl_account
-
mail(:to => @to, :subject => subject)
-
end
-
-
def digest_notify(d)
-
preparing_recipients(d)
-
@e_certs = d[1].uniq
-
subject = "SSL.com reminder - ssl certificate expiring digest"
-
mail(:to => @to, :subject => subject)
-
end
-
-
def past_expired_digest_notice(d, interval)
-
@first, @last = interval.first.to_i, interval.last.to_i
-
preparing_recipients(d)
-
u_certs = d[1].map(&:cert).map{|c|
-
[c.common_name.downcase, c]}
-
cn, ed = u_certs.transpose
-
if cn.uniq.count != cn.count
-
diff = cn & cn.uniq
-
d_hash_arry = diff.map do |dn|
-
{dn => u_certs.select do |name, cert|
-
cert if name == dn
-
end.sort{|a,b|a[1].expiration_date <=> b[1].expiration_date}.last}
-
end
-
d_hash_arry.each do |d_hash|
-
d_hash.each do |k,v|
-
d[1].each do |ec|
-
d[1].delete(ec) if ec.cert.common_name.downcase == k &&
-
ec.cert.expiration_date != v[1].expiration_date
-
end
-
end
-
end
-
end
-
@e_certs = d[1].uniq
-
subject = "SSL.com reminder - ssl certificate expiration digest"
-
mail(:to => @to, :subject => subject)
-
end
-
-
private
-
-
def prep(cert, contact)
-
@name, @cert, @contact =
-
"#{contact.first_name.strip} #{contact.last_name.strip}", cert, contact
-
@to="#{@name} <#{contact.email}>"
-
end
-
-
def preparing_recipients(recips)
-
first_name, last_name, emails = recips[0].split(",")
-
@name = "#{first_name.strip} #{last_name.strip}"
-
@to=[]
-
@unsubscribe='un-'+SecureRandom.hex(1)+Time.now.to_i.to_s(32)
-
emails.split(/[, ;]/).each do |e|
-
if e=~EmailValidator::EMAIL_FORMAT && !DO_NOT_SEND.any?{|dns|e=~Regexp.new(dns, "i")}
-
@to<<e
-
end
-
end
-
end
-
end
-
class Ability
-
include CanCan::Ability
-
-
def initialize(user)
-
# Define abilities for the passed in user here. For example:
-
#
-
@user = user || User.new # guest user (not logged in)
-
@user.roles.each { |role| send(role.name) if Ability.method_defined?(role.name) }
-
-
# if user.admin?
-
# can :manage, :all
-
# else
-
# can :read, :all
-
# end
-
#
-
# The first argument to `can` is the action you are giving the user permission to do.
-
# If you pass :manage it will apply to every action. Other common actions here are
-
# :read, :create, :update and :destroy.
-
#
-
# The second argument is the resource the user can perform the action on. If you pass
-
# :all it will apply to every resource. Otherwise pass a Ruby class of the resource.
-
#
-
# The third argument is an optional hash of conditions to further filter the objects.
-
# For example, here the user can only update published articles.
-
#
-
# can :update, Article, :published => true
-
#
-
# See the wiki for details: https://github.com/ryanb/cancan/wiki/Defining-Abilities
-
can do |action, subject_class, subject|
-
@user.permissions.find_all_by_action(aliases_for_action(action.to_s)).any? do |permission|
-
permission.subject_class == subject_class.to_s &&
-
(subject.nil? || permission.subject_id.nil? || permission.subject_id == subject.id)
-
end
-
end
-
can :manage, :all if @user.has_role? :admin
-
end
-
-
def certificates_requestor
-
can :create, CertificateOrder, ssl_account_id: @user.ssl_account_id
-
can :delete, CertificateOrder, ssl_account_id: @user.ssl_account_id
-
can :update, CertificateOrder, ssl_account_id: @user.ssl_account_id
-
can :view, CertificateOrder, ssl_account_id: @user.ssl_account_id
-
can :validate_certificate, CertificateOrder, ssl_account_id: @user.ssl_account_id
-
end
-
-
def certificates_approver
-
can :approve, CertificateOrder, ssl_account_id: @user.ssl_account_id
-
end
-
-
def certificates_manager
-
certificates_requestor
-
certificates_approver
-
can :manage, CertificateOrder, ssl_account_id: @user.ssl_account_id
-
end
-
-
# for technical or other ppl where prices do not have to be shown
-
def prices_restricted
-
cannot :view_price, Order, id: @user.ssl_account.order_ids
-
end
-
-
def orders_requestor
-
can :create, Order, id: @user.ssl_account.order_ids
-
can :view, Order, id: @user.ssl_account.order_ids
-
end
-
-
def orders_approver
-
can :approve, Order, id: @user.ssl_account.order_ids
-
end
-
-
def orders_manager
-
orders_requestor
-
orders_approver
-
can :manage, Order, id: @user.ssl_account.order_ids
-
end
-
-
def developer
-
can :develop, CertificateOrder
-
end
-
-
def admin
-
certificates_manager
-
can :manage, Bill
-
end
-
-
end
-
class AccessToken < OauthToken
-
validates_presence_of :user, :secret
-
before_create :set_authorized_at
-
-
# Implement this to return a hash or array of the capabilities the access token has
-
# This is particularly useful if you have implemented user defined permissions.
-
# def capabilities
-
# {:invalidate=>"/oauth/invalidate",:capabilities=>"/oauth/capabilities"}
-
# end
-
-
protected
-
-
def set_authorized_at
-
self.authorized_at = Time.now
-
end
-
end
-
class Address < ActiveRecord::Base
-
ADDRESS_MAPPING = { :address1 => :street1, :address2 => :street2,
-
:city => :locality, :state => :region, :zip => :postal_code }
-
-
def read_attribute_with_mapping(attr_name)
-
read_attribute_without_mapping(ADDRESS_MAPPING[attr_name] || attr_name)
-
end
-
alias_method_chain :read_attribute, :mapping
-
-
end
-
class AdministrativeContact < CertificateContact
-
end
-
class Affiliate < ActiveRecord::Base
-
belongs_to :ssl_account
-
has_many :line_items
-
has_many :certificate_orders, through: :line_items, :source => :sellable, :source_type => 'CertificateOrder'
-
has_many :orders, through: :line_items
-
has_many :visitor_tokens
-
has_many :tracked_urls, through: :visitor_tokens
-
-
PROFILE_COLUMNS = %w(display_name tagline description)
-
COMPANY_COLUMNS = %w(organization website address1 address2
-
postal_code city state country)
-
ADMIN_COLUMNS = %w(first_name last_name email phone)
-
PAYMENT_COLUMNS = %w(payout_threshold payout_method)
-
EPASSPORTE_ACCOUNT = %w(epassporte_account)
-
CHECKS_PAYABLE_TO = %w(checks_payable_to)
-
BANK_COLUMNS = %w(bank_name bank_routing_number bank_account_number swift_code)
-
REQUIRED_COLUMNS = %w(type_organization organization website address1
-
postal_code city state country) + ADMIN_COLUMNS
-
FORM_COLUMNS=%w(type_organization)+ADMIN_COLUMNS+COMPANY_COLUMNS+
-
PAYMENT_COLUMNS
-
#guarantee 10% profit on each sale
-
ar=[]
-
0.step((1-0.1-Settings.studio_fee_rate.to_f)*100,
-
5){|i|ar<<i}
-
AFFILIATE_PAYOUT_BRACKETS=ar.collect{|i| [i.to_s+"%",(i.to_f/100).to_s]}
-
CHECK = "check"
-
WIRE = "wired"
-
EPASSPORTE = "epassporte"
-
PAYPAL = "paypal"
-
BUSINESS = "business"
-
INDIVIDUAL = "individual"
-
-
validates_presence_of *((REQUIRED_COLUMNS).map(&:intern))
-
validates_presence_of *((BANK_COLUMNS).map(&:intern)+[:if => Proc.new{|affiliate| affiliate.payout_method == WIRE }])
-
validates_presence_of :checks_payable_to, :if => Proc.new{|affiliate| affiliate.payout_method == CHECK }
-
validates_presence_of :epassporte_account, :if => Proc.new{|affiliate| affiliate.payout_method == EPASSPORTE }
-
#validates_presence_of :tax_number, :state, :if => Proc.new{|affiliate| affiliate.american? }
-
validates_presence_of :organization, :if => Proc.new{|affiliate| affiliate.type_organization == BUSINESS }
-
validates_length_of *((FORM_COLUMNS+EPASSPORTE_ACCOUNT+
-
CHECKS_PAYABLE_TO+BANK_COLUMNS).map(&:intern)+[:maximum => 100])
-
#validates_length_of :display_name, :maximum => 30
-
#validates_uniqueness_of :display_name, :case_sensitive=>false, :allow_nil=>true, :allow_blank=>true
-
#validates_length_of :tagline, :maximum => 60
-
#validates_length_of :description, :maximum => 500
-
validates_length_of :email, :within => 3..100
-
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9A-Z]+\.)+[a-zA-Z]{2,})\z/
-
-
#include Workflow
-
#workflow do
-
# state :new do
-
# event :submit_profile, :transitions_to => :profile_submitted
-
# end
-
#
-
# state :profile_submitted do
-
# event :approve, :transitions_to => :approved
-
# event :disapprove, :transitions_to => :disapproved
-
# event :cancel, :transitions_to => :new
-
# end
-
#
-
# state :disapproved do
-
# event :approve, :transitions_to => :approved
-
# event :cancel, :transitions_to => :new
-
# end
-
#
-
# state :approved do
-
# event :cancel, :transitions_to => :new
-
# end
-
#end
-
-
-
def american?
-
country == "United States"
-
end
-
-
def payout_method
-
read_attribute("payout_method") || CHECK
-
end
-
-
def payout_threshold
-
read_attribute("payout_threshold") || "50"
-
end
-
-
def type_organization
-
read_attribute("type_organization") || BUSINESS
-
end
-
-
def view_count
-
self[:view_count] || 0
-
end
-
-
def display_name
-
read_attribute(:display_name) || organization || "Studio"
-
end
-
-
# gives all the urls visited, even after the landed url. Too much detail for affiliates to use
-
def tracked_urls_count
-
tracked_urls.group{url}.count
-
end
-
-
def landed_urls
-
code="%code/#{id}"
-
code_t = code+"/"
-
tu=Tracking.joins{tracked_url}.where{(tracked_url.url=~code) | (tracked_url.url =~code_t)}.map(&:tracked_url)
-
urls=tu.map(&:url).uniq
-
{}.tap do |h|
-
urls.each{|u|
-
h.merge! u => tu.select{|t|t.url==u}.count
-
}
-
end
-
end
-
-
# this function gets the unique referral urls
-
def referral_urls
-
r=Tracking.affiliate_referers(id).pluck(:referer_id).compact
-
TrackedUrl.where{id >> r}.pluck(:url)
-
end
-
-
def sold_to
-
orders.map(&:billable).map(&:users)
-
end
-
-
end
-
require "declarative_authorization/maintenance"
-
-
class ApiCertificateCreate < ApiCertificateRequest
-
attr_accessor :csr_obj, # temporary csr object
-
:certificate_url, :receipt_url, :smart_seal_url, :validation_url,
-
:order_number, :order_amount, :order_status
-
-
NON_EV_SSL_PERIODS = %w(365 730 1095 1461 1826)
-
EV_SSL_PERIODS = %w(365 730)
-
EV_CS_PERIODS = %w(365 730 1095)
-
FREE_PERIODS = %w(30 90)
-
-
DCV_METHODS = %w(email http_csr_hash cname_csr_hash https_csr_hash)
-
-
validates :account_key, :secret_key, :csr, presence: true
-
validates :period, presence: true, format: /\d+/,
-
inclusion: {in: ApiCertificateRequest::NON_EV_SSL_PERIODS,
-
message: "needs to be one of the following: #{NON_EV_SSL_PERIODS.join(', ')}"}, if: lambda{|c|!(c.is_ev? || c.is_dv?)}
-
validates :period, presence: true, format: {with: /\d+/},
-
inclusion: {in: ApiCertificateRequest::EV_SSL_PERIODS,
-
message: "needs to be one of the following: #{EV_SSL_PERIODS.join(', ')}"}, if: lambda{|c|c.is_ev?}
-
# validates :server_count, presence: true, if: lambda{|c|c.is_wildcard?}
-
validates :server_software, presence: true, format: {with: /\d+/}, inclusion:
-
{in: ServerSoftware.pluck(:id).map(&:to_s),
-
message: "needs to be one of the following: #{ServerSoftware.pluck(:id).map(&:to_s).join(', ')}"},
-
if: "Settings.require_server_software_w_csr_submit"
-
validates :organization_name, presence: true, if: lambda{|c|!c.is_dv? || c.csr_obj.organization.blank?}
-
validates :post_office_box, presence: {message: "is required if street_address_1 is not specified"},
-
if: lambda{|c|!c.is_dv? && c.street_address_1.blank?} #|| c.parsed_field("POST_OFFICE_BOX").blank?}
-
validates :street_address_1, presence: {message: "is required if post_office_box is not specified"},
-
if: lambda{|c|!c.is_dv? && c.post_office_box.blank?} #|| c.parsed_field("STREET1").blank?}
-
validates :locality_name, presence: true, if: lambda{|c|!c.is_dv? || c.csr_obj.locality.blank?}
-
validates :state_or_province_name, presence: true, if: lambda{|c|!c.is_dv? || c.csr_obj.state.blank?}
-
validates :postal_code, presence: true, if: lambda{|c|!c.is_dv?} #|| c.parsed_field("POSTAL_CODE").blank?}
-
validates :country_name, presence: true, inclusion:
-
{in: Country.accepted_countries, message: "needs to be one of the following: #{Country.accepted_countries.join(', ')}"},
-
if: lambda{|c|c.csr_obj && c.csr_obj.country.try("blank?")}
-
#validates :registered_country_name, :incorporation_date, if: lambda{|c|c.is_ev?}
-
validates :dcv_email_address, email: true, unless: lambda{|c|c.dcv_email_address.blank?}
-
validates :dcv_method, inclusion: {in: ApiCertificateCreate::DCV_METHODS,
-
message: "needs to one of the following: #{DCV_METHODS.join(', ')}"}, if: lambda{|c|c.dcv_method}
-
validates :email_address, email: true, unless: lambda{|c|c.email_address.blank?}
-
validates :contact_email_address, email: true, unless: lambda{|c|c.contact_email_address.blank?}
-
validates :business_category, format: {with: /[bcd]/}, unless: lambda{|c|c.business_category.blank?}
-
validates :common_names_flag, format: {with: /[01]/}, unless: lambda{|c|c.common_names_flag.blank?}
-
# use code instead of serial allows attribute changes without affecting the cert name
-
validates :product, presence: true, format: {with: /\d{3}/},
-
inclusion: {in: PRODUCTS.keys.map(&:to_s),
-
message: "needs to one of the following: #{PRODUCTS.keys.map(&:to_s).join(', ')}"}
-
validates :is_customer_validated, format: {with: /(y|n|yes|no|true|false|1|0)/i}
-
validates :is_customer_validated, presence: true, unless: lambda{|c|c.is_dv? && c.csr_obj.is_intranet?}
-
#validate :common_name, :is_not_ip, if: lambda{|c|!c.is_dv?}
-
validates_presence_of :verify_dcv_email_address, on: :create
-
-
before_validation do
-
if new_record?
-
if self.csr # a single domain validation
-
self.dcv_method ||= "http_csr_hash"
-
self.csr_obj = Csr.new(body: self.csr) # this is only for validation and does not save
-
unless self.csr_obj.errors.empty?
-
self.errors[:csr] << "has problems and or errors"
-
end
-
elsif self.api_requestable.is_a?(CertificateName) # a multi domain validation
-
end
-
end
-
end
-
-
def create_certificate_order
-
# create certificate
-
@certificate = Certificate.find_by_serial(PRODUCTS[self.product.to_sym])
-
co_params = {duration: period}
-
co_params.merge!({is_test: self.test})
-
co_params.merge!({domains: self.domains}) if(is_ucc? && self.domains)
-
csr = self.csr_obj
-
csr.save
-
certificate_order = api_requestable.certificate_orders.build(co_params)
-
certificate_content=CertificateContent.new(
-
csr: csr, server_software_id: self.server_software)
-
certificate_order.certificate_contents << certificate_content
-
@certificate_order = Order.setup_certificate_order(certificate: @certificate, certificate_order: certificate_order,
-
duration: self.period)
-
@certificate_order.renewal = self.api_requestable.certificate_orders.find_by_ref(self.renewal_id) if self.renewal_id
-
order = api_requestable.purchase(@certificate_order)
-
order.cents = @certificate_order.attributes_before_type_cast["amount"].to_f
-
unless self.test
-
errors[:funded_account] << "Not enough funds in the account to complete this purchase. Please deposit more funds." if
-
(order.amount.cents > api_requestable.funded_account.amount.cents)
-
end
-
if errors.blank?
-
if certificate_content.valid? &&
-
apply_funds(certificate_order: @certificate_order, ssl_account: api_requestable, order: order)
-
if certificate_content.save
-
setup_certificate_content(
-
certificate_order: certificate_order,
-
certificate_content: certificate_content,
-
ssl_account: api_requestable)
-
end
-
return @certificate_order
-
else
-
return certificate_content
-
end
-
end
-
errors
-
end
-
-
def setup_certificate_content(options)
-
certificate_order= options[:certificate_order]
-
cc = options[:certificate_content]
-
cc.add_ca(options[:certificate_order].ssl_account) if options[:certificate_order].external_order_number.blank?
-
cc.create_registrant(
-
company_name: self.organization_name,
-
department: self.organization_unit_name,
-
po_box: self.post_office_box,
-
address1: self.street_address_1,
-
address2: self.street_address_2,
-
address3: self.street_address_3,
-
city: self.locality_name,
-
state: self.state_or_province_name,
-
postal_code: self.postal_code,
-
country: self.country_name)
-
if cc.csr_submitted?
-
cc.provide_info!
-
CertificateContent::CONTACT_ROLES.each do |role|
-
c = CertificateContact.new
-
r = options[:ssl_account].reseller
-
CertificateContent::RESELLER_FIELDS_TO_COPY.each do |field|
-
c.send((field+'=').to_sym, r.send(field.to_sym))
-
end
-
c.company_name = r.organization
-
c.country = Country.find_by_name_caps(r.country.upcase).iso1_code if
-
Country.find_by_name_caps(r.country.upcase)
-
c.clear_roles
-
c.add_role! role
-
cc.certificate_contacts << c
-
cc.update_attribute(role+"_checkbox", true) unless
-
role==CertificateContent::ADMINISTRATIVE_ROLE
-
end
-
cc.provide_contacts!
-
cc.pend_validation! !certificate_order.is_test
-
end
-
end
-
-
def apply_funds(options)
-
order = options[:order]
-
funded_account = options[:ssl_account].funded_account
-
funded_account.cents -= order.cents unless @certificate_order.is_test
-
if funded_account.cents >= 0 and order.line_items.size > 0
-
funded_account.deduct_order = true
-
if order.cents > 0
-
order.save
-
order.mark_paid!
-
end
-
Authorization::Maintenance::without_access_control do
-
funded_account.save unless @certificate_order.is_test
-
end
-
options[:certificate_order].pay! true
-
end
-
end
-
-
def verify_dcv_email_address
-
if self.dcv_methods
-
-
elsif self.dcv_email_address
-
emails=ComodoApi.domain_control_email_choices(self.domain ? self.domain :
-
self.csr_obj.common_name).email_address_choices
-
errors[:dcv_email_address]<< "must be one of the following: #{emails.join(", ")}" unless
-
emails.include?(self.dcv_email_address)
-
end
-
end
-
end
-
require "declarative_authorization/maintenance"
-
-
class ApiCertificateCreate_v1_4 < ApiCertificateRequest
-
include CertificateType
-
attr_accessor :csr_obj, # temporary csr object
-
:certificate_url, :receipt_url, :smart_seal_url, :validation_url, :order_number, :order_amount, :order_status,
-
:api_request, :api_response, :error_code, :error_message, :eta, :send_to_ca, :ref, :renewal_id, :saved_registrant,
-
:certificates
-
-
DCV_FAILURE_ACTIONS = %w(remove ignore)
-
-
PRODUCTS = Settings.api_product_codes.to_hash.stringify_keys
-
-
DCV_METHODS = %w(email http_csr_hash cname_csr_hash https_csr_hash)
-
DEFAULT_DCV_METHOD = "http_csr_hash"
-
DEFAULT_DCV_METHOD_COMODO = "HTTPCSRHASH"
-
-
validates :account_key, :secret_key, presence: true
-
validates :ref, presence: true, if: lambda{|c|['update_v1_4', 'show_v1_4'].include?(c.action)}
-
validates :csr, presence: true, unless: "ref.blank? || is_processing?"
-
validates :period, presence: true, format: /\d+/,
-
inclusion: {in: ApiCertificateRequest::NON_EV_SSL_PERIODS,
-
message: "needs to be one of the following: #{NON_EV_SSL_PERIODS.join(', ')}"}, if: lambda{|c| (c.is_dv? || c.is_ov?) &&
-
!c.is_free? && c.ref.blank? && ['create_v1_4'].include?(c.action)}
-
validates :period, presence: true, format: {with: /\d+/},
-
inclusion: {in: ApiCertificateRequest::EV_SSL_PERIODS,
-
message: "needs to be one of the following: #{EV_SSL_PERIODS.join(', ')}"}, if: lambda{|c|c.is_ev? && c.ref.blank? &&
-
['create_v1_4'].include?(c.action)}
-
validates :period, presence: true, format: {with: /\d+/},
-
inclusion: {in: ApiCertificateRequest::EV_CS_PERIODS,
-
message: "needs to be one of the following: #{EV_CS_PERIODS.join(', ')}"}, if: lambda{|c|c.is_evcs? && c.ref.blank? &&
-
['create_v1_4'].include?(c.action)}
-
validates :period, presence: true, format: {with: /\d+/},
-
inclusion: {in: ApiCertificateRequest::FREE_PERIODS,
-
message: "needs to be one of the following: #{FREE_PERIODS.join(', ')}"}, if: lambda{|c|c.is_free? && c.ref.blank? &&
-
['create_v1_4'].include?(c.action)}
-
validates :product, presence: true, format: {with: /\d{3}/},
-
inclusion: {in: PRODUCTS.keys.map(&:to_s),
-
message: "needs to one of the following: #{PRODUCTS.keys.map(&:to_s).join(', ')}"}, if:
-
lambda{|c|['create_v1_4'].include?(c.action)}
-
validates :server_software, presence: true, format: {with: /\d+/}, inclusion:
-
{in: ServerSoftware.pluck(:id).map(&:to_s),
-
message: "needs to be one of the following: #{ServerSoftware.pluck(:id).map(&:to_s).join(', ')}"},
-
if: lambda{|c|c.is_server? && c.csr && Settings.require_server_software_w_csr_submit}
-
validates :organization_name, presence: true, if: lambda{|c|c.csr && (!c.is_dv? && c.csr_obj.organization.blank?)}
-
validates :post_office_box, presence: {message: "is required if street_address_1 is not specified"},
-
if: lambda{|c|!c.is_dv? && c.street_address_1.blank? && c.csr} #|| c.parsed_field("POST_OFFICE_BOX").blank?}
-
validates :street_address_1, presence: {message: "is required if post_office_box is not specified"},
-
if: lambda{|c|!c.is_dv? && c.post_office_box.blank? &&c.csr} #|| c.parsed_field("STREET1").blank?}
-
validates :locality_name, presence: true, if: lambda{|c|c.csr && (!c.is_dv? && c.csr_obj.locality.blank?)}
-
validates :state_or_province_name, presence: true, if: lambda{|c|csr && (!c.is_dv? && c.csr_obj.state.blank?)}
-
validates :postal_code, presence: true, if: lambda{|c|c.csr && !c.is_dv?} #|| c.parsed_field("POSTAL_CODE").blank?}
-
validates :country_name, presence: true, inclusion:
-
{in: Country.accepted_countries, message: "needs to be one of the following: #{Country.accepted_countries.join(', ')}"},
-
if: lambda{|c| c.csr && c.csr_obj && c.csr_obj.country.try("blank?")}
-
#validates :registered_country_name, :incorporation_date, if: lambda{|c|c.is_ev?}
-
validates :dcv_method, inclusion: {in: ApiCertificateCreate::DCV_METHODS,
-
message: "needs to one of the following: #{DCV_METHODS.join(', ')}"}, if: lambda{|c|c.dcv_method}
-
validates :contact_email_address, email: true, unless: lambda{|c|c.contact_email_address.blank?}
-
validates :business_category, format: {with: /[bcd]/}, unless: lambda{|c|c.business_category.blank?}
-
validates :common_names_flag, format: {with: /[01]/}, unless: lambda{|c|c.common_names_flag.blank?}
-
validates :unique_value, format: {with: /[a-zA-Z0-9]{1,20}/}, unless: lambda{|c|c.unique_value.blank?}
-
# use code instead of serial allows attribute changes without affecting the cert name
-
validate :verify_dcv, on: :create, if: "!domains.blank?"
-
# validate :validate_contacts, if: "api_requestable && api_requestable.reseller.blank? && !csr.blank?"
-
validate :validate_callback, unless: lambda{|c|c.callback.blank?}
-
validate :renewal_exists, if: lambda{|c|c.renewal_id}
-
-
before_validation do
-
retrieve_registrant
-
self.period = period.to_s unless period.blank?
-
self.product = product.to_s unless product.blank?
-
if new_record?
-
if self.csr # a single domain validation
-
self.server_software ||= ServerSoftware::OTHER
-
self.dcv_method ||= "http_csr_hash"
-
self.csr_obj = Csr.new(body: self.csr) # this is only for validation and does not save
-
self.csr_obj.csr_unique_values.build(unique_value: unique_value) unless unique_value.blank?
-
unless self.csr_obj.errors.empty?
-
self.errors[:csr] << "has problems and or errors"
-
end
-
elsif self.api_requestable.is_a?(CertificateName) # a multi domain validation
-
#TODO add dcv validation
-
end
-
end
-
# verify_domain_limits
-
end
-
-
def create_certificate_order
-
certificate = Certificate.for_sale.find_by_serial(PRODUCTS[self.product.to_s]+api_requestable.tier_suffix)
-
co_params = {duration: period, is_test: self.test, ext_customer_ref: external_order_number}
-
co = api_requestable.certificate_orders.build(co_params)
-
if self.csr
-
# process csr
-
csr = self.csr_obj
-
csr.save
-
else
-
# or make a certificate voucher
-
co.preferred_payment_order = 'prepaid'
-
end
-
certificate_content=CertificateContent.new(
-
csr: csr, server_software_id: self.server_software, domains: get_domains,
-
ca: certificate.cas.ssl_account_or_general_default(api_requestable).last)
-
co.certificate_contents << certificate_content
-
@certificate_order = Order.setup_certificate_order(
-
certificate: certificate,
-
certificate_order: co,
-
duration: self.period.to_i/365
-
)
-
order = api_requestable.purchase(@certificate_order)
-
order.cents = @certificate_order.attributes_before_type_cast["amount"].to_f
-
-
if errors.blank?
-
if certificate_content.valid?
-
apply_funds(
-
certificate_order: @certificate_order,
-
ssl_account: api_requestable,
-
order: order
-
)
-
return self unless errors.blank?
-
order.save
-
if csr && certificate_content.save
-
setup_certificate_content(
-
certificate_order: @certificate_order,
-
certificate_content: certificate_content,
-
ssl_account: api_requestable,
-
contacts: self.contacts)
-
end
-
certificate_content.url_callbacks.create(callback) if callback
-
return @certificate_order
-
else
-
return certificate_content
-
end
-
end
-
self
-
end
-
-
def replace_certificate_order
-
@certificate_order = self.find_certificate_order
-
self.domains = {self.csr_obj.common_name=>{"dcv"=>"http_csr_hash"}} if self.domains.blank?
-
# caa_check_domains = parameters_to_hash["caa_check_domains"].split(',')
-
caa_check_domains = self.caa_check_domains.split(',') unless self.caa_check_domains.blank?
-
-
if @certificate_order.is_a?(CertificateOrder)
-
# CAA Checking for domains what has been validated and no passed for CAA.
-
unless caa_check_domains.blank?
-
@certificate_order.certificate_content.certificate_names.find_by_domains(caa_check_domains).each do |cn|
-
CaaCheck.pass?(@certificate_order.ref, cn, cn.certificate_content)
-
end
-
end
-
-
@certificate_order.update_attribute(:external_order_number, self.ca_order_number) if (self.admin_submitted && self.ca_order_number)
-
@certificate_order.update_attribute(:ext_customer_ref, self.external_order_number) if self.external_order_number
-
@certificate_order.is_test = self.test
-
-
if @certificate_order.certificate_content && @certificate_order.certificate_content.pending_validation? &&
-
(@certificate_order.external_order_number || !@certificate_order.certificate_content.ca.blank?)
-
cn_keys = self.cert_names.keys
-
-
@certificate_order.certificate_content.certificate_names.includes{:domain_control_validations}.
-
each do |certificate_name|
-
# if cn_keys.include? certificate_name.id.to_s
-
# certificate_name.update_column(:name, self.cert_names[certificate_name.id.to_s])
-
# else
-
# certificate_name.destroy
-
# end
-
-
if cn_keys.exclude? certificate_name.name
-
unless @certificate_order.certificate_content.ca_id.nil?
-
dcvs = certificate_name.domain_control_validations
-
dcvs.destroy_all if dcvs.size > 0
-
end
-
-
certificate_name.destroy
-
-
# Remove Domain from Notification Group
-
NotificationGroup.auto_manage_cert_name(@certificate_order.certificate_content, 'delete', certificate_name)
-
elsif self.cert_names[certificate_name.name] != certificate_name.name
-
dcv = certificate_name.domain_control_validations.last
-
if !dcv || (dcv && !dcv.satisfied?)
-
certificate_name.update_column(:name, self.cert_names[certificate_name.name])
-
NotificationGroup.auto_manage_cert_name(@certificate_order.certificate_content, 'update', certificate_name)
-
elsif dcv && dcv.satisfied?
-
self.cert_names[certificate_name.name] = certificate_name.name
-
end
-
end
-
end
-
cn_vals = self.cert_names.map{|k, v|v}
-
-
# @certificate_order.certificate_content.update_attribute(:domains, self.domains.keys)
-
@certificate_order.certificate_content.update_attribute(:domains, cn_vals)
-
@certificate_order.certificate_content.dcv_domains({domains: self.domains, emails: self.dcv_candidate_addresses})
-
-
# domainNames = self.domains.keys.join(',')
-
# domainDcvs = self.domains.keys.map{|k|"#{@certificate_order.certificate_content.certificate_names.find_by_name(k).try(:last_dcv_for_comodo)}"}.join(',')
-
-
#send to comodo
-
if @certificate_order.certificate_content.ca_id.nil?
-
comodo_auto_replace_ssl(
-
certificate_order: @certificate_order,
-
domainNames: cn_vals.join(',')
-
# domainDcvs: domainDcvs
-
)
-
end
-
end
-
-
return @certificate_order
-
end
-
self
-
end
-
-
def update_certificate_order
-
@certificate_order = self.find_certificate_order
-
self.domains = {self.csr_obj.common_name=>{"dcv"=>"http_csr_hash"}} if self.domains.blank?
-
caa_check_domains = self.caa_check_domains.split(',') unless self.caa_check_domains.blank?
-
-
if @certificate_order.is_a?(CertificateOrder)
-
# CAA Checking for domains what has been validated and no passed for CAA.
-
unless caa_check_domains.blank?
-
@certificate_order.certificate_content.certificate_names.find_by_domains(caa_check_domains).each do |cn|
-
CaaCheck.pass?(@certificate_order.ref, cn, cn.certificate_content)
-
end
-
end
-
-
@certificate_order.update_attribute(:external_order_number, self.ca_order_number) if # from API
-
(self.admin_submitted && self.ca_order_number)
-
@certificate_order.update_attribute(:ext_customer_ref, self.external_order_number) if self.external_order_number
-
# choose the right ca_certificate_id for submit to Comodo
-
@certificate_order.is_test = self.test
-
-
#assume updating domain validation, already sent to comodo
-
if @certificate_order.certificate_content && @certificate_order.certificate_content.pending_validation? &&
-
(@certificate_order.external_order_number || !@certificate_order.certificate_content.ca.blank?)
-
#set domains
-
-
# if @certificate_order.certificate.is_basic? || @certificate_order.certificate.is_free? || @certificate_order.certificate.is_high_assurance?
-
# cnames = @certificate_order.certificate_content.domains
-
# domain_strs = []
-
# self.domains.keys.each do |key|
-
# domain_strs << key unless domain_strs.include? key
-
#
-
# if !key.include?('www.') && cnames.include?('www.' + key)
-
# domain_strs << ('www.' + key)
-
# end
-
# end
-
# @certificate_order.certificate_content.update_attribute(:domains, domain_strs)
-
# else
-
# @certificate_order.certificate_content.update_attribute(:domains, self.domains.keys)
-
# end
-
-
@certificate_order.certificate_content.update_attribute(:domains, self.domains.keys)
-
@certificate_order.certificate_content.dcv_domains({domains: self.domains, emails: self.dcv_candidate_addresses})
-
-
#send to comodo if ca_id is nil
-
if @certificate_order.certificate_content.ca_id.nil?
-
comodo_auto_update_dcv(certificate_order: @certificate_order)
-
end
-
else
-
if self.csr_obj
-
certificate_content = @certificate_order.certificate_contents.build
-
csr = self.csr_obj
-
csr.save
-
certificate_content.csr = csr
-
certificate_content.server_software_id = server_software
-
certificate_content.submit_csr!
-
certificate_content.domains = domains.keys unless domains.blank?
-
if errors.blank?
-
if certificate_content.save
-
setup_certificate_content(
-
certificate_order: @certificate_order,
-
certificate_content: certificate_content,
-
contacts: self.contacts)
-
certificate_content.url_callbacks.create(callback) if callback
-
else
-
return certificate_content
-
end
-
end
-
else
-
certificate_content = @certificate_order.certificate_content
-
certificate_content.domains = domains.keys unless domains.blank?
-
send_dcv(certificate_content)
-
end
-
end
-
-
return @certificate_order
-
end
-
-
self
-
end
-
-
def certificate_order_callback
-
@certificate_order=self.find_certificate_order
-
if @certificate_order.is_a?(CertificateOrder)
-
self.callback_hook = @certificate_order.certificate_content.callback(self.callback)
-
end
-
self
-
end
-
-
def update_certificate_content_contacts
-
@certificate_order=self.find_certificate_order
-
if @certificate_order.is_a?(CertificateOrder)
-
contacts = self.contacts
-
# if !@certificate_order.certificate_content ||
-
# (@certificate_order.certificate_content && @certificate_order.certificate_content.issued?)
-
# byebug
-
# cc = @certificate_order.certificate_contents.build
-
#
-
# if cc.save
-
# CertificateContent::CONTACT_ROLES.each do |role|
-
# byebug
-
# c = CertificateContact.new(contacts[role])
-
# c.clear_roles
-
# c.add_role! role
-
# unless c.valid?
-
# errors[:contacts] << {role.to_sym => c.errors}
-
# else
-
# cc.certificate_contacts << c
-
# cc.update_attribute(role+"_checkbox", true) unless
-
# role==CertificateContent::ADMINISTRATIVE_ROLE
-
# end
-
# end
-
# end
-
# byebug
-
# else
-
c = @certificate_order.certificate_content.certificate_contacts
-
c.each do |contact|
-
role = contact.roles[0]
-
if role
-
contact.update_attributes(contacts[role])
-
end
-
unless contact.valid?
-
errors[:contacts] << {role.to_sym => c[role].errors}
-
end
-
end
-
# end
-
end
-
self
-
end
-
-
def comodo_auto_replace_ssl(options={send_to_ca: true})
-
res = ComodoApi.auto_replace_ssl(options)
-
comodo_auto_update_dcv(options) if res[0] == '0'
-
end
-
-
# this update dcv method to comodo for each domain
-
def comodo_auto_update_dcv(options={send_to_ca: true})
-
names = options[:certificate_order].certificate_content.certificate_names.find_by_domains(self.domains.keys)
-
names.map do |name|
-
# ComodoApi.delay.auto_update_dcv(dcv:
-
ComodoApi.auto_update_dcv(dcv:
-
name.domain_control_validations.last, send_to_ca: options[:send_to_ca])
-
end
-
end
-
-
DomainJob = Struct.new(:cc, :acc, :dcv_failure_action, :domains, :dcv_candidate_addresses) do
-
def perform
-
cc.dcv_domains({domains: (domains || [cc.csr.common_name]), emails: dcv_candidate_addresses,
-
dcv_failure_action: dcv_failure_action})
-
cc.pend_validation!(ca_certificate_id: acc[:ca_certificate_id],
-
send_to_ca: acc[:send_to_ca] || true) unless cc.pending_validation?
-
end
-
end
-
-
def setup_certificate_content(options)
-
cc = options[:certificate_content]
-
cc.registrant.destroy unless cc.registrant.blank?
-
cc.add_ca(options[:certificate_order].ssl_account) if options[:certificate_order].external_order_number.blank?
-
cc.create_registrant(
-
company_name: self.organization_name,
-
department: self.organization_unit_name,
-
po_box: self.post_office_box,
-
address1: self.street_address_1,
-
address2: self.street_address_2,
-
address3: self.street_address_3,
-
city: self.locality_name,
-
state: self.state_or_province_name,
-
postal_code: self.postal_code,
-
country: self.country_name || csr_obj.country)
-
if cc.csr_submitted?
-
cc.provide_info!
-
if Contact.optional_contacts? && contacts && contacts[:saved_contacts]
-
sc = contacts[:saved_contacts]
-
if sc && sc.is_a?(Array) && sc.any?
-
sc.each do |c_id|
-
c = CertificateContact.new(
-
retrieve_saved_contact({saved_contact: c_id}, ['roles']).merge(parent_id: c_id)
-
)
-
if c.valid?
-
cc.certificate_contacts << c
-
else
-
errors[:contacts] << {
-
"saved_contact_#{c_id}" => "Failed to create contact: #{c.errors.full_messages.join(', ')}."
-
}
-
end
-
end
-
end
-
else
-
CertificateContent::CONTACT_ROLES.each do |role|
-
c = if options[:contacts] && (options[:contacts][role] || options[:contacts][:all])
-
CertificateContact.new(retrieve_saved_contact(
-
options[:contacts][(options[:contacts][role] ? role : :all)].to_utf8,
-
%w(company_name department)
-
))
-
elsif api_requestable.reseller
-
attributes = api_requestable.reseller.attributes.select do |attr, value|
-
(CertificateContact.column_names-%w(id created_at)).include?(attr.to_s)
-
end
-
contact = CertificateContact.new
-
contact.assign_attributes(attributes, without_protection: true)
-
contact
-
end
-
unless c.blank?
-
c.clear_roles
-
c.add_role! role
-
unless c.valid?
-
errors[:contacts] << {role.to_sym => c.errors}
-
else
-
cc.certificate_contacts << c
-
cc.update_attribute(role+"_checkbox", true) unless
-
role==CertificateContent::ADMINISTRATIVE_ROLE
-
end
-
end
-
end
-
end
-
cc.provide_contacts!
-
options[:certificate_order].orphaned_certificate_contents remove: true
-
if options[:certificate_order].domains_validated?
-
options[:certificate_order].validate!
-
api_log_entry=options[:certificate_order].apply_for_certificate(mapping: cc.ca)
-
if api_log_entry
-
if api_log_entry.instance_of?(SslcomCaRequest) and api_log_entry.response=~/Check CAA/
-
self.order_status =
-
"CAA validation failed. See https://#{Settings.portal_domain}/how-to/configure-caa-records-to-authorize-ssl-com/"
-
end
-
cc.issue! unless api_log_entry.certificate_chain.blank?
-
end
-
else
-
send_dcv(cc)
-
end if options[:certificate_order].certificate.is_server?
-
end
-
end
-
-
def send_dcv(cc)
-
if self.debug=="true" || (self.domains && self.domains.count <= Validation::COMODO_EMAIL_LOOKUP_THRESHHOLD)
-
cc.dcv_domains({domains: self.domains, emails: self.dcv_candidate_addresses,
-
dcv_failure_action: self.options.blank? ? nil : self.options['dcv_failure_action']})
-
cc.pend_validation!(ca_certificate_id: ca_certificate_id, send_to_ca: send_to_ca || true) unless cc.pending_validation?
-
else
-
job_group = Delayed::JobGroups::JobGroup.create!
-
job_group.enqueue(DomainJob.new(cc, {ca_certificate_id: self.ca_certificate_id, send_to_ca: self.send_to_ca || true},
-
self.options.blank? ? nil : self.options['dcv_failure_action'], self.domains,
-
self.dcv_candidate_addresses))
-
job_group.mark_queueing_complete
-
end
-
end
-
-
def apply_funds(options)
-
order = options[:order]
-
if order.line_items.size > 0
-
paid = if parameters_to_hash['billing_profile'].nil?
-
apply_to_funded_account(options)
-
else
-
apply_to_billing_profile(options)
-
end
-
if paid
-
order.mark_paid!
-
options[:certificate_order].pay!(true)
-
end
-
end
-
end
-
-
def apply_to_funded_account(options)
-
applied = false
-
order = options[:order]
-
funded_account = options[:ssl_account].funded_account
-
if funded_account.cents < order.cents && !debug_mode?
-
self.errors[:funded_account] = "Not enough funds in the account to complete this purchase! Please deposit additional #{Money.new(order.cents - funded_account.cents).format}."
-
end
-
if errors[:funded_account].blank?
-
self.errors.delete :billing_profile
-
self.errors.delete :funded_account
-
funded_account.cents -= order.cents
-
funded_account.deduct_order = true
-
applied = true
-
Authorization::Maintenance::without_access_control do
-
funded_account.save unless debug_mode?
-
end
-
end
-
applied
-
end
-
-
def apply_to_billing_profile(options)
-
response = false
-
last_digits = parameters_to_hash['billing_profile']
-
if last_digits
-
profile = options[:ssl_account].billing_profiles.find_by(last_digits: last_digits)
-
if profile
-
gateway_response = options[:order].purchase(
-
profile.build_credit_card,
-
profile.build_info(Order::SSL_CERTIFICATE)
-
.merge(owner_email: options[:ssl_account].get_account_owner.email)
-
)
-
if gateway_response.success?
-
response = true
-
else
-
self.errors[:billing_profile] = gateway_response.message
-
end
-
else
-
self.errors[:billing_profile] = "Could not find billing profile ending in #{billing_profile} for this account!"
-
end
-
end
-
response
-
end
-
-
def renewal_exists
-
self.errors[:renewal_id] << "renewal_id #{self.renewal_id} does not exist or is invalid" if
-
self.api_requestable.certificate_orders.find_by_ref(self.renewal_id).blank?
-
end
-
-
# must belong to a list of acceptable email addresses
-
def verify_dcv
-
#if submitting domains, then a csr must have been submitted on this or a previous request
-
if !csr.blank? || is_processing?
-
self.dcv_candidate_addresses = {}
-
if self.domains.is_a?(Array)
-
values = Array.new(self.domains.count,"dcv"=>"HTTP_CSR_HASH")
-
self.domains = (self.domains.zip(values)).to_h
-
end
-
self.domains.each do |k,v|
-
unless v["dcv"] =~ /https?/i || v["dcv"] =~ /cname/i
-
unless v["dcv"]=~EmailValidator::EMAIL_FORMAT
-
errors[:domains] << "domain control validation for #{k} failed. #{v["dcv"]} is an invalid email address."
-
else
-
self.dcv_candidate_addresses[k]=[]
-
# self.dcv_candidate_addresses[k]=ComodoApi.domain_control_email_choices(k).email_address_choices
-
# errors[:domains] << "domain control validation for #{k} failed. Invalid email address #{v["dcv"]} was submitted but only #{self.dcv_candidate_addresses[k].join(", ")} are valid choices." unless
-
# self.dcv_candidate_addresses[k].include?(v["dcv"])
-
end
-
end
-
v["dcv_failure_action"] ||= "ignore"
-
end
-
elsif csr.blank?
-
# allow domains without the csr so commented out below
-
# errors[:domains] << "csr has not been submitted yet."
-
elsif !api_requestable.certificate_content.pending_validation?
-
errors[:domains] << "certificate order is not in validation stage."
-
else
-
errors[:domains] << "domain control validation failed. Please contact support@ssl.com for more information."
-
end
-
end
-
-
def validate_contacts
-
if contacts
-
if !contacts.is_a?(Hash)
-
errors[:contacts] << "expecting hash"
-
return false
-
end
-
errors[:contacts] = {}
-
if Contact.optional_contacts? && contacts[:saved_contacts]
-
sc = contacts[:saved_contacts]
-
if sc && sc.is_a?(Array) && sc.any?
-
found = 0
-
sc.each {|c| found += 1 if api_requestable.all_saved_contacts.find_by(id: c.to_i)}
-
errors[:contacts].push(saved_contacts: "Contacts with ids #{sc.join(', ')} do not exist.") unless found > 0
-
else
-
errors[:contacts].push(saved_contacts: "Zero contacts provided, please pass a list of saved contact ids. E.g.: [1, 5, 6].")
-
end
-
else
-
CertificateContent::CONTACT_ROLES.each do |role|
-
if (contacts[role] || contacts['all'])
-
c_role = contacts[role] ? role : 'all'
-
attrs = retrieve_saved_contact(contacts[c_role], [c_role])
-
extra = (attrs.keys - permit_contact_fields).flatten
-
if attrs[:saved_contact] # failed to find saved contact by id
-
errors[:contacts].last[:role] = c_role
-
elsif !extra.empty?
-
msg = {c_role.to_sym => "The following parameters are invalid: #{extra.join(', ')}"}
-
errors[:contacts].last.merge!(msg)
-
elsif !CertificateContact.new(attrs.to_utf8.merge(roles: [role])).valid?
-
r = CertificateContact.new(attrs.to_utf8.merge(roles: [role]))
-
r.valid?
-
errors[:contacts].last.merge!(c_role.to_sym => r.errors)
-
elsif attrs['country'].blank? || Country.find_by_iso1_code(attrs['country'].upcase).blank?
-
msg = {c_role.to_sym => "The 'country' parameter has an invalid value of '#{attrs['country']}'"}
-
errors[:contacts].last.merge!(msg)
-
end
-
else
-
msg = {role.to_sym => "contact information missing"}
-
errors[:contacts].last.merge!(msg)
-
end
-
end
-
end
-
else
-
errors[:contacts] << "parameter required"
-
end
-
cur_err = errors[:contacts].reject(&:empty?)
-
errors.delete(:contacts)
-
errors.add(:contacts, cur_err) if cur_err.any?
-
errors.get(:contacts) ? false : true
-
end
-
-
def validate_callback
-
if !callback.is_a?(Hash)
-
errors[:callback] << "expecting hash"
-
return false
-
else
-
cb = UrlCallback.new(callback)
-
errors[:callback] = cb.errors unless cb.valid?
-
end
-
end
-
-
def retrieve_registrant
-
id = self.saved_registrant
-
if id
-
found = self.api_requestable.saved_registrants.find_by(id: id.to_i)
-
if found
-
self.organization_name = found.company_name
-
self.organization_unit_name = found.department
-
self.post_office_box = found.po_box
-
self.street_address_1 = found.address1
-
self.street_address_2 = found.address2
-
self.street_address_3 = found.address3
-
self.locality_name = found.city
-
self.state_or_province_name = found.state
-
self.postal_code = found.postal_code
-
self.country_name = found.country
-
else
-
errors[:saved_registrant].push(id: "Registrant with id=#{id} does not exist.")
-
end
-
end
-
end
-
-
def retrieve_saved_contact(attributes, extra_attributes=[])
-
new_attrs = attributes # { saved_contact: contact_id }
-
if attributes && attributes.is_a?(Hash)
-
id = attributes[:saved_contact]
-
if id
-
found = self.api_requestable.all_saved_contacts.find_by(id: id.to_i)
-
if found
-
keepers = permit_contact_fields + extra_attributes - ['all']
-
new_attrs = found.attributes.keep_if {|k,_| keepers.include? k}
-
else
-
unless extra_attributes.include?('all') && errors[:contacts].count > 1
-
errors[:contacts].push(id: "Contact with id=#{id} does not exist.")
-
end
-
end
-
end
-
end
-
new_attrs
-
end
-
-
def is_processing?
-
co=@certificate_order || find_certificate_order
-
co.is_a?(CertificateOrder) && (co.certificate_content.try("contacts_provided?") ||
-
co.certificate_content.try("pending_validation?")) ? true : false
-
end
-
-
def domains
-
@domains || parameters_to_hash["domains"]
-
end
-
-
def cert_names
-
@cert_names || parameters_to_hash["cert_names"]
-
end
-
-
def caa_check_domains
-
if Settings.enable_caa
-
@caa_check_domains || parameters_to_hash["caa_check_domains"]
-
else
-
''
-
end
-
end
-
-
def ref
-
super
-
end
-
-
def test_update_dcv
-
a=ApiCertificateCreate_v1_4.find{|a|a.domains && (a.domains.keys.count) > 2 && a.ref && a.find_certificate_order.try(:external_order_number) && a.find_certificate_order.is_test?}
-
a.comodo_auto_update_dcv(send_to_ca: false, certificate_order: a.find_certificate_order)
-
end
-
-
def debug_mode?
-
self.test && !Rails.env.test?
-
end
-
-
def get_domains
-
if csr_obj && csr_obj.valid? && domains.nil?
-
self.domains={}
-
csr_obj.all_names(san: true).each do |name|
-
self.domains.merge!({name.downcase => {dcv: 'HTTP_CSR_HASH'}}.with_indifferent_access)
-
end
-
end
-
-
if domains.is_a? Hash
-
domains.keys
-
elsif domains.is_a? String
-
[domains]
-
else
-
domains
-
end
-
end
-
-
def verify_domain_limits
-
unless domains.nil?
-
max = if is_ucc? || is_evucc?
-
500
-
elsif is_dv? || is_ev? || is_ov? || is_wildcard?
-
1
-
elsif is_premium?
-
3
-
else
-
1
-
end
-
if domains.count > max
-
errors[:domains] << "You have exceeded the maximum of #{max} domain(s) or subdomains for this certificate."
-
end
-
end
-
end
-
-
def permit_contact_fields
-
CertificateContent::RESELLER_FIELDS_TO_COPY + %w(organization organization_unit country saved_contact)
-
end
-
end
-
class ApiCertificateEnrollment < ApiCertificateRequest
-
include OrdersHelper
-
-
validates :certificate_id, :duration, :domains, :account_key, :secret_key, :approver_id, presence: true
-
-
def certificate_enrollment
-
return false unless api_requestable
-
-
@certificate = Certificate.find parameters_to_hash["certificate_id"]
-
@domains = parse_domains(parameters_to_hash["domains"])
-
-
enroll
-
-
return true if @order && @order.persisted? && @order.valid?
-
end
-
-
def enroll
-
# STEP 1: Setup Certificate Orders
-
@certificate_orders = setup_certificate_orders
-
-
# STEP 2: Setup Order
-
setup_order
-
-
# STEP 3: Add Certificate Orders to Order
-
@order.add_certificate_orders(@certificate_orders)
-
-
if @order.save
-
# STEP 4: Paid status for Certificate Orders, Order is Invoiced
-
pay_certificate_orders
-
update_enrollment_request
-
-
# STEP 5: Create Registrants
-
setup_registrants unless iv_only?
-
-
# STEP 6: Validate Individual Validations (via Delayed Job)
-
@order.smime_client_enrollment_validate(approver_id)
-
end
-
end
-
-
private
-
-
def setup_certificate_orders
-
if @certificate
-
@domains.inject([]) do |cos, email|
-
co = CertificateOrder.new(
-
has_csr: false,
-
ssl_account: api_requestable,
-
duration: parameters_to_hash["duration"]
-
)
-
co.certificate_contents << CertificateContent.new(domains: [])
-
cos << Order.setup_certificate_order(
-
certificate: @certificate,
-
certificate_order: co
-
)
-
cos
-
end
-
else
-
[]
-
end
-
end
-
-
def setup_order
-
invoice_descr = require_emails_as_domains? ? "emails" : "domains"
-
@order = EnrollmentOrder.new(
-
state: "invoiced",
-
approval: "approved",
-
invoice_description: "Certificate enrollment for #{@certificate_orders.count} #{invoice_descr}.",
-
description: Order::CERTIFICATE_ENROLLMENT,
-
billable_id: @certificate_orders.first.ssl_account.try(:id),
-
billable_type: "SslAccount",
-
invoice_id: Invoice.get_or_create_for_team(api_requestable).try(:id),
-
)
-
end
-
-
def pay_certificate_orders
-
@order.cached_certificate_orders.update_all(
-
ssl_account_id: api_requestable.try(:id), workflow_state: "paid"
-
)
-
end
-
-
def update_enrollment_request
-
req_id = parameters_to_hash["request_id"]
-
if req_id
-
req = api_requestable.certificate_enrollment_requests.find req_id
-
req.update(
-
order_id: @order.id,
-
status: CertificateEnrollmentRequest::statuses[:approved]
-
) if req
-
end
-
end
-
-
def setup_registrants
-
registrant_params = api_requestable.epki_registrant.attributes
-
.except(*%w{id created_at updated_at type domains roles})
-
.merge({
-
"parent_id" => api_requestable.epki_registrant.id,
-
"status" => Contact::statuses[:validated]
-
})
-
ccs = CertificateContent.joins(certificate_order: :orders)
-
.where(orders: {id: @order.id})
-
ccs.each do |cc|
-
cc.create_registrant(registrant_params)
-
cc.create_locked_registrant(registrant_params)
-
cc.save
-
end
-
end
-
-
def require_emails_as_domains?
-
@certificate.is_code_signing? || @certificate.is_smime_or_client?
-
end
-
-
def iv_only?
-
@certificate.is_client_basic? || @certificate.is_client_pro?
-
end
-
-
def parse_domains(domains)
-
if require_emails_as_domains?
-
smime_client_parse_emails(domains)
-
else
-
@domains
-
end
-
end
-
end
-
class ApiCertificateQuote < ApiCertificateRequest
-
QUERY_TYPE = %w(order_status_only end_certificate all_certificates ca_bundle)
-
RESPONSE_TYPE = %w(zip netscape pkcs7 individually)
-
RESPONSE_ENCODING = %w(base64 binary)
-
-
validates :account_key, :secret_key, :ref, presence: true
-
validates :query_type, presence: true,
-
inclusion: {in: ApiCertificateRetrieve::QUERY_TYPE,
-
message: "needs to be one of the following: #{QUERY_TYPE.join(', ')}"}
-
validates :response_type, presence: true,
-
inclusion: {in: ApiCertificateRetrieve::RESPONSE_TYPE,
-
message: "needs to be one of the following: #{RESPONSE_TYPE.join(', ')}"}, if: lambda{|c|c.response_type}
-
validates :response_encoding, presence: true,
-
inclusion: {in: ApiCertificateRetrieve::RESPONSE_ENCODING,
-
message: "needs to be one of the following: #{RESPONSE_ENCODING.join(', ')}"}, if: lambda{|c|c.response_encoding}
-
validates :show_validity_period, format: /[YNyn]/, if: lambda{|c|c.show_validity_period}
-
validates :show_domains, format: /[YNyn]/, if: lambda{|c|c.show_domains}
-
validates :show_ext_status, format: /[YNyn]/, if: lambda{|c|c.show_ext_status}
-
validates_presence_of :order_exists, if: lambda{|c|c.ref}
-
-
attr_accessor :validity_period, :domains, :ext_status, :certificates, :order_status, :certificate_order,
-
:common_name, :subject_alternative_names, :effective_date, :expiration_date, :algorithm
-
-
def initialize(attributes = {})
-
super
-
self.query_type ||= "all_certificates"
-
self.response_type ||= "individually"
-
self.response_encoding ||= "base64"
-
end
-
-
def order_exists
-
self.certificate_order=CertificateOrder.find_by_ref(self.ref)
-
errors[:ref] << "doesn't exist'" unless self.certificate_order
-
end
-
-
end
-
require "declarative_authorization/maintenance"
-
-
class ApiCertificateReprocess < ApiCertificateRequest
-
include CertificateType
-
attr_accessor :csr_obj, :certificate_url, :receipt_url, :smart_seal_url, :validation_url,
-
:order_number, :order_amount, :order_status
-
-
NON_EV_SSL_PERIODS = %w(365 730 1095 1461 1826)
-
EV_SSL_PERIODS = %w(365 730)
-
-
PRODUCTS = Settings.api_product_codes.to_hash.stringify_keys
-
-
validates :account_key, :secret_key, :csr, :ref, presence: true
-
validates :period, presence: true, format: /\d+/,
-
inclusion: {in: ApiCertificateRequest::NON_EV_SSL_PERIODS,
-
message: "needs to be one of the following: #{ApiCertificateRequest::NON_EV_SSL_PERIODS.join(', ')}"}, if: lambda{|c|!(c.is_ev? || c.is_dv?)}
-
validates :period, presence: true, format: {with: /\d+/},
-
inclusion: {in: ApiCertificateRequest::EV_SSL_PERIODS,
-
message: "needs to be one of the following: #{ApiCertificateRequest::EV_SSL_PERIODS.join(', ')}"}, if: lambda{|c|c.is_ev?}
-
# validates :server_count, presence: true, if: lambda{|c|c.is_wildcard?}
-
validates :server_software, presence: true, format: {with: /\d+/}, inclusion:
-
{in: ServerSoftware.pluck(:id).map(&:to_s),
-
message: "needs to be one of the following: #{ServerSoftware.pluck(:id).map(&:to_s).join(', ')}"},
-
if: "Settings.require_server_software_w_csr_submit"
-
validates :organization_name, presence: true, if: lambda{|c|!c.is_dv? || c.csr_obj.organization.blank?}
-
validates :post_office_box, presence: {message: "is required if street_address_1 is not specified"},
-
if: lambda{|c|!c.is_dv? && c.street_address_1.blank?} #|| c.parsed_field("POST_OFFICE_BOX").blank?}
-
validates :street_address_1, presence: {message: "is required if post_office_box is not specified"},
-
if: lambda{|c|!c.is_dv? && c.post_office_box.blank?} #|| c.parsed_field("STREET1").blank?}
-
validates :locality_name, presence: true, if: lambda{|c|!c.is_dv? || c.csr_obj.locality.blank?}
-
validates :state_or_province_name, presence: true, if: lambda{|c|!c.is_dv? || c.csr_obj.state.blank?}
-
validates :postal_code, presence: true, if: lambda{|c|!c.is_dv?} #|| c.parsed_field("POSTAL_CODE").blank?}
-
validates :country_name, presence: true, inclusion:
-
{in: Country.accepted_countries, message: "needs to be one of the following: #{Country.accepted_countries.join(', ')}"},
-
if: lambda{|c|c.csr_obj && c.csr_obj.country.try("blank?")}
-
#validates :registered_country_name, :incorporation_date, if: lambda{|c|c.is_ev?}
-
validates :dcv_email_address, email: true, unless: lambda{|c|c.dcv_email_address.blank?}
-
validates :dcv_method, inclusion: {in: ApiCertificateCreate::DCV_METHODS,
-
message: "needs to one of the following: #{ApiCertificateCreate::DCV_METHODS.join(', ')}"}, if: lambda{|c|c.dcv_method}
-
validates :email_address, email: true, unless: lambda{|c|c.email_address.blank?}
-
validates :contact_email_address, email: true, unless: lambda{|c|c.contact_email_address.blank?}
-
validates :business_category, format: {with: /[bcd]/}, unless: lambda{|c|c.business_category.blank?}
-
validates :common_names_flag, format: {with: /[01]/}, unless: lambda{|c|c.common_names_flag.blank?}
-
# use code instead of serial allows attribute changes without affecting the cert name
-
validates :product, presence: true, format: {with: /\d{3}/},
-
inclusion: {in: PRODUCTS.keys.map(&:to_s),
-
message: "needs to one of the following: #{PRODUCTS.keys.map(&:to_s).join(', ')}"}
-
validates :is_customer_validated, format: {with: /(y|n|yes|no|true|false|1|0)/i}
-
validates :is_customer_validated, presence: true, unless: lambda{|c|c.is_dv? && c.csr_obj.is_intranet?}
-
#validate :common_name, :is_not_ip, if: lambda{|c|!c.is_dv?}
-
validates_presence_of :verify_dcv_methods, on: :create
-
-
after_initialize do
-
if new_record? && self.csr
-
self.dcv_method ||= "http_csr_hash"
-
self.csr_obj = Csr.new(body: self.csr)
-
unless self.csr_obj.errors.empty?
-
self.errors[:csr] << "has problems and or errors"
-
end
-
end
-
end
-
-
#TODO finish this
-
def verify_dcv_methods
-
# if non ucc then look for email address, http_csr_hash, or dns
-
#if self.dcv_email_address && dcv_method=="http_csr_hash"
-
# emails=ComodoApi.domain_control_email_choices(self.domain ? self.domain :
-
# self.csr_obj.common_name).email_address_choices
-
# errors[:dcv_email_address]<< "must be one of the following: #{emails.join(", ")}" unless
-
# emails.include?(self.dcv_email_address)
-
#end
-
true
-
end
-
-
def create_certificate_order
-
# create certificate
-
@certificate = Certificate.find_by_serial(PRODUCTS[self.product.to_sym])
-
co_params = {duration: period}
-
co_params.merge!({is_test: self.test})
-
co_params.merge!({domains: self.domains}) if(is_ucc? && self.domains)
-
certificate_order = current_user.ssl_account.cached_certificate_orders.build(co_params)
-
certificate_content=certificate_order.certificate_contents.build(
-
csr: self.csr_obj, server_software_id: self.server_software)
-
certificate_content.certificate_order = certificate_order
-
@certificate_order = Order.setup_certificate_order(certificate: @certificate, certificate_order: certificate_order)
-
order = current_user.ssl_account.purchase(@certificate_order)
-
order.cents = @certificate_order.attributes_before_type_cast["amount"].to_f
-
unless self.test
-
errors[:funded_account] << "Not enough funds in the account to complete this purchase. Please deposit more funds." if
-
(order.amount.cents > current_user.ssl_account.funded_account.amount.cents)
-
end
-
if errors.blank?
-
if certificate_content.valid? &&
-
apply_funds(certificate_order: @certificate_order, current_user: current_user, order: order)
-
if certificate_content.save
-
setup_certificate_content(
-
certificate_order: certificate_order,
-
certificate_content: certificate_content,
-
current_user: current_user)
-
end
-
return @certificate_order
-
else
-
return certificate_content
-
end
-
end
-
end
-
-
def setup_certificate_content(options)
-
certificate_order= options[:certificate_order]
-
cc = options[:certificate_content]
-
cc.add_ca(options[:certificate_order].ssl_account) if options[:certificate_order].external_order_number.blank?
-
cc.create_registrant(
-
company_name: self.organization_name,
-
department: self.organization_unit_name,
-
po_box: self.post_office_box,
-
address1: self.street_address_1,
-
address2: self.street_address_2,
-
address3: self.street_address_3,
-
city: self.locality_name,
-
state: self.state_or_province_name,
-
postal_code: self.postal_code,
-
country: self.country_name)
-
if cc.csr_submitted?
-
cc.provide_info!
-
CertificateContent::CONTACT_ROLES.each do |role|
-
c = CertificateContact.new
-
r = options[:current_user].ssl_account.reseller
-
CertificateContent::RESELLER_FIELDS_TO_COPY.each do |field|
-
c.send((field+'=').to_sym, r.send(field.to_sym))
-
end
-
c.company_name = r.organization
-
c.country = Country.find_by_name_caps(r.country.upcase).iso1_code if
-
Country.find_by_name_caps(r.country.upcase)
-
c.clear_roles
-
c.add_role! role
-
cc.certificate_contacts << c
-
cc.update_attribute(role+"_checkbox", true) unless
-
role==CertificateContent::ADMINISTRATIVE_ROLE
-
end
-
cc.provide_contacts!
-
cc.pend_validation! # !certificate_order.is_test
-
end
-
end
-
-
def setup_certificate_order(certificate, certificate_order)
-
duration = self.period
-
certificate_order.certificate_content.duration = duration
-
if certificate.is_ucc? || certificate.is_wildcard?
-
psl = certificate.items_by_server_licenses.find { |item|
-
item.value==duration.to_s }
-
so = SubOrderItem.new(:product_variant_item=>psl,
-
:quantity =>certificate_order.server_licenses.to_i,
-
:amount =>psl.amount*certificate_order.server_licenses.to_i)
-
certificate_order.sub_order_items << so
-
if certificate.is_ucc?
-
pd = certificate.items_by_domains.find_all { |item|
-
item.value==duration.to_s }
-
additional_domains = (certificate_order.domains.try(:size) || 0) - Certificate::UCC_INITIAL_DOMAINS_BLOCK
-
so = SubOrderItem.new(:product_variant_item=>pd[0],
-
:quantity =>Certificate::UCC_INITIAL_DOMAINS_BLOCK,
-
:amount =>pd[0].amount*Certificate::UCC_INITIAL_DOMAINS_BLOCK)
-
certificate_order.sub_order_items << so
-
if additional_domains > 0
-
so = SubOrderItem.new(:product_variant_item=>pd[1],
-
:quantity =>additional_domains,
-
:amount =>pd[1].amount*additional_domains)
-
certificate_order.sub_order_items << so
-
end
-
end
-
end
-
unless certificate.is_ucc?
-
pvi = certificate.items_by_duration.find { |item| item.value==duration.to_s }
-
so = SubOrderItem.new(:product_variant_item=>pvi, :quantity=>1,
-
:amount =>pvi.amount)
-
certificate_order.sub_order_items << so
-
end
-
certificate_order.amount = certificate_order.
-
sub_order_items.map(&:amount).sum
-
certificate_order.certificate_contents[0].
-
certificate_order = certificate_order
-
certificate_order
-
end
-
-
def apply_funds(options)
-
order = options[:order]
-
@account_total = funded_account = options[:current_user].ssl_account.funded_account
-
funded_account.cents -= order.cents unless @certificate_order.is_test
-
if funded_account.cents >= 0 and order.line_items.size > 0
-
funded_account.deduct_order = true
-
if order.cents > 0
-
order.save
-
order.mark_paid!
-
end
-
Authorization::Maintenance::without_access_control do
-
funded_account.save unless @certificate_order.is_test
-
end
-
options[:certificate_order].pay! true
-
end
-
end
-
end
-
class ApiCertificateRequest < CaApiRequest
-
extend Memoist
-
include CertificateType
-
attr_accessor :csr_obj, :current_user, :test, :action, :admin_submitted
-
-
ORDER_STATUS = ["waiting for domain control validation",
-
"waiting for documents", "pending validation", "validated", "pending issuance", "issued", "revoked", "canceled"]
-
-
PRODUCTS = Settings.api_product_codes.to_hash.stringify_keys
-
-
NON_EV_SSL_PERIODS = %w(365 730 1095 1461 1826)
-
EV_SSL_PERIODS = %w(365 730)
-
EV_CS_PERIODS = %w(365 730 1095)
-
FREE_PERIODS = %w(30 90)
-
-
CREATE_ACCESSORS_1_4 = [:account_key, :secret_key, :product, :period, :server_count, :server_software, :domains,
-
:domain, :common_names_flag, :csr, :organization_name, :organization_unit_name, :post_office_box,
-
:street_address_1, :street_address_2, :street_address_3, :locality_name, :state_or_province_name,
-
:postal_code, :country_name, :duns_number, :company_number, :registered_locality_name,
-
:registered_state_or_province_name, :registered_country_name, :incorporation_date,
-
:assumed_name, :business_category, :email_address, :contact_email_address, :dcv_email_address,
-
:ca_certificate_id, :is_customer_validated, :hide_certificate_reference, :external_order_number,
-
:dcv_candidate_addresses, :dcv_method, :ref, :contacts, :options, :renewal_id, :billing_profile, :certificates]
-
-
UPDATE_ACCESSORS_1_4 = [:cert_names, :caa_check_domains]
-
-
ACCESSORS = [:account_key, :secret_key, :product, :period, :server_count, :server_software, :domains, :options,
-
:domain, :common_names_flag, :csr, :organization_name, :organization_unit_name, :post_office_box,
-
:street_address_1, :street_address_2, :street_address_3, :locality_name, :state_or_province_name,
-
:postal_code, :country_name, :duns_number, :company_number, :registered_locality_name,
-
:registered_state_or_province_name, :registered_country_name, :incorporation_date,
-
:assumed_name, :business_category, :email_address, :contact_email_address, :dcv_email_address,
-
:ca_certificate_id, :is_customer_validated, :hide_certificate_reference, :external_order_number,
-
:dcv_candidate_addresses, :dcv_method, :dcv_methods, :certificate_ref, :contacts, :admin_funded,
-
:ca_order_number, :debug, :api_call, :billing_profile, :callback, :unique_value, :pub_key, :signed_certificates]
-
-
REPROCESS_ACCESSORS = [:account_key, :secret_key, :server_count, :server_software, :domains,
-
:domain, :common_names_flag, :csr, :organization_name, :organization_unit_name, :post_office_box,
-
:street_address_1, :street_address_2, :street_address_3, :locality_name, :state_or_province_name,
-
:postal_code, :country_name, :duns_number, :company_number, :registered_locality_name,
-
:registered_state_or_province_name, :registered_country_name, :incorporation_date,
-
:assumed_name, :business_category, :email_address, :contact_email_address,
-
:ca_certificate_id, :is_customer_validated, :hide_certificate_reference, :external_order_number,
-
:dcv_methods, :ref, :options]
-
-
RETRIEVE_ACCESSORS = [:account_key, :secret_key, :ref, :query_type, :response_type, :response_encoding,
-
:show_validity_period, :show_domains, :show_ext_status, :validations, :registrant, :start, :end, :filter,
-
:show_subscriber_agreement, :product_name, :search, :cert_results, :cert_common_name, :callback_hook]
-
-
DETAILED_ACCESSORS = [:menu, :sub_main, :cert_details, :smart_seal, :id, :artifacts_status,
-
:publish_to_site_seal, :viewing_method, :publish_to_site_seal_approval, :is_admin]
-
-
UPLOAD_ACCESSORS = [:checkout_in_progress, :is_dv, :is_dv_or_basic, :is_ev, :community_name, :all_domains,
-
:acceptable_file_types, :other_party_request, :subject, :validation_rules, :success_message]
-
-
DCV_EMAIL_RESEND_ACCESSORS = [:account_key, :secret_key, :ref, :email_address]
-
-
DCV_EMAILS_ACCESSORS = [:account_key, :secret_key, :domain]
-
-
REVOKE_ACCESSORS = [:account_key, :secret_key, :ref, :reason, :serials]
-
-
PRETEST_ACCESSOR = [:is_passed]
-
-
CERTIFICATE_ENROLLMENT_ACCESSORS = [:certificate_id, :domains, :duration, :approver_id, :is_ordered]
-
-
# be sure to review wrap_parameters in ApiCertificateRequestsController when modifying attr_accessor below
-
attr_accessor *(
-
ACCESSORS +
-
RETRIEVE_ACCESSORS +
-
DCV_EMAILS_ACCESSORS +
-
REVOKE_ACCESSORS +
-
PRETEST_ACCESSOR +
-
DETAILED_ACCESSORS +
-
UPLOAD_ACCESSORS +
-
UPDATE_ACCESSORS_1_4 +
-
CERTIFICATE_ENROLLMENT_ACCESSORS
-
).uniq
-
-
before_validation(on: :create) do
-
ac=api_credential
-
unless ac.blank?
-
self.api_requestable = ac.ssl_account
-
else
-
errors[:login] << "account_key not found or wrong secret_key"
-
false
-
end
-
end
-
-
after_initialize do
-
if new_record?
-
self.ca ||= "ssl.com"
-
end
-
end
-
-
def api_credential
-
(self.account_key && self.secret_key) ?
-
ApiCredential.find_by_account_key_and_secret_key(self.account_key, self.secret_key) : nil
-
end
-
memoize :api_credential
-
-
def find_certificate_order(field=:ref)
-
if defined?(field) && self.send(field)
-
if self.api_requestable.users.find_all(&:active?).find(&:is_admin?)
-
self.admin_submitted = true
-
if co=CertificateOrder.find_by_ref(self.send(field))
-
self.api_requestable = co.ssl_account
-
co
-
else
-
errors[:certificate_order] << "Certificate order not found for ref #{self.send(field)}."
-
nil
-
end
-
else
-
self.api_requestable.certificate_orders.find_by_ref(self.send(field)) ||
-
(errors[:certificate_order] << "Certificate order not found for ref #{self.send(field)}." ; nil)
-
end
-
end
-
end
-
-
# find signed certificates based on the `serials` api parameter
-
def find_signed_certificates(certificate_order=nil)
-
return nil if certificate_order.blank? && !self.admin_submitted
-
klass = (self.admin_submitted && certificate_order.blank?) ? SignedCertificate.unscoped :
-
certificate_order.signed_certificates
-
certs = []
-
([]).tap do |certs|
-
if defined?(:serials) && self.serials
-
(self.serials.is_a?(Array) ? serials : [serials]).map do |serial|
-
if sc=klass.find_by_serial(serial)
-
certs<<sc
-
else
-
errors[:signed_certificate] <<
-
"Signed certificate not found for serial #{serial}#{" within certificate order ref #{certificate_order.ref}" if certificate_order}."
-
break
-
end
-
end
-
else
-
certs<<klass
-
end
-
end
-
end
-
-
# find signed certificates based on the `public_key` api parameter
-
def find_signed_certificates_by_public_key
-
public_key = JSON.parse(self.parameters)["pub_key"]
-
-
total_signed_certs = self.api_requestable.users.flatten.compact
-
.map(&:certificate_orders).flatten.compact
-
.map(&:signed_certificates).flatten.compact.map{|sc| sc.id}
-
-
if total_signed_certs.empty?
-
[]
-
else
-
SignedCertificate.unscoped.where(id: total_signed_certs).by_public_key(public_key.gsub("\r\n", "\n")).flatten.compact
-
end
-
end
-
-
# def find_certificate_orders(search,offset,limit)
-
def find_certificate_orders(search,options={})
-
is_test = self.test ? "is_test" : "not_test"
-
co =
-
# TODO if ApiCredential.roles include? Role.find(6) super_user
-
if false # self.api_requestable.users.find(&:is_admin?)
-
self.admin_submitted = true
-
CertificateOrder.send(is_test)
-
else
-
self.api_requestable.certificate_orders.send(is_test)
-
end
-
# end.offset(offset).limit(limit)
-
co = co.search_with_csr(search,options) if search
-
if co
-
self.filter=="vouchers" ? co.send("unused_credits") : co
-
else
-
(errors[:certificate_orders] << "Certificate orders not found.")
-
end
-
end
-
-
def ref
-
read_attribute(:ref) || @ref || JSON.parse(self.parameters)["ref"]
-
end
-
-
def validations_from_comodo(co) #if named 'validations', it's executed twice
-
mdc_validation = ComodoApi.mdc_status(co)
-
ds = mdc_validation.domain_status
-
cc = co.certificate_content
-
cns = co.certificate_names.includes(:domain_control_validations)
-
dcvs = {}.tap do |dcv|
-
(co.certificate.is_ucc? ? co.all_domains : [co.common_name]).each do |domain|
-
last = (cns.find_all{|cn|cn.name==domain}).map(&:domain_control_validations).flatten.compact.last ||
-
(co.csr.domain_control_validations.flatten.compact.last if (co.csr && co.csr.common_name==domain))
-
unless last.blank?
-
dcv.merge! domain=>{"attempted_on"=>last.created_at,
-
"dcv_method"=>(last.email_address || last.dcv_method),
-
"status"=>(ds && ds[domain]) ? ds[domain]["status"].downcase : "not yet available"}
-
end
-
end if co.all_domains
-
end
-
dcvs.blank? ? nil : dcvs #be consistent with the api results by returning null if empty
-
end
-
-
def retry
-
%x"curl -k -H 'Accept: application/json' -H 'Content-type: application/json' -X #{request_method.upcase} -d '#{parameters}' #{request_url.gsub(".com",".local:3000").gsub("http:","https:")}"
-
end
-
-
def serial
-
PRODUCTS[self.product.to_s] if product
-
end
-
-
def target_certificate
-
@target_certificate ||=
-
if serial
-
Certificate.find_by_serial(serial)
-
elsif ref
-
CertificateOrder.unscoped.find_by_ref(ref).certificate
-
end
-
end
-
-
%W(is_premium_ssl? is_dv_or_basic? is_basic? is_multi? is_document_signing? is_personal? is_wildcard?
-
is_ucc? is_free? is_premium_ssl? is_evucc? is_wildcard?).each do |name|
-
define_method(name) do
-
target_certificate.send(name) if target_certificate
-
end
-
end
-
alias_method "is_premium?".to_sym, "is_premium_ssl?".to_sym
-
-
def is_not_ip
-
true
-
end
-
end
-
class ApiCertificateRetrieve < ApiCertificateRequest
-
QUERY_TYPE = %w(order_status_only end_certificate all_certificates ca_bundle)
-
RESPONSE_TYPE = %w(zip netscape pkcs7 individually)
-
RESPONSE_ENCODING = %w(base64 binary)
-
-
validates :account_key, :secret_key, presence: true
-
validates :ref, presence: true, if: lambda{|c|c.start.blank? && c.end.blank?}
-
validates :query_type, presence: true,
-
inclusion: {in: ApiCertificateRetrieve::QUERY_TYPE,
-
message: "needs to be one of the following: #{QUERY_TYPE.join(', ')}"}
-
validates :response_type, presence: true,
-
inclusion: {in: ApiCertificateRetrieve::RESPONSE_TYPE,
-
message: "needs to be one of the following: #{RESPONSE_TYPE.join(', ')}"}, if: lambda{|c|c.response_type}
-
validates :response_encoding, presence: true,
-
inclusion: {in: ApiCertificateRetrieve::RESPONSE_ENCODING,
-
message: "needs to be one of the following: #{RESPONSE_ENCODING.join(', ')}"}, if: lambda{|c|c.response_encoding}
-
validates :show_validity_period, format: /[YNyn]/, if: lambda{|c|c.show_validity_period}
-
validates :show_subscriber_agreement, format: /[YNyn]/, if: lambda{|c|c.show_subscriber_agreement}
-
validates :show_domains, format: /[YNyn]/, if: lambda{|c|c.show_domains}
-
validates :show_ext_status, format: /[YNyn]/, if: lambda{|c|c.show_ext_status}
-
validate :order_exists, if: lambda{|c|c.ref}
-
-
attr_accessor :validity_period, :domains, :ext_status, :certificates, :order_status, :certificate_order,
-
:common_name, :subject_alternative_names, :effective_date, :expiration_date, :algorithm,
-
:site_seal_code, :domains_qty_purchased, :wildcard_qty_purchased, :description, :subscriber_agreement,
-
:order_date, :product_type, :period, :private_cache_key
-
-
def initialize(attributes = {})
-
super
-
self.query_type ||= "all_certificates"
-
self.response_type ||= "individually"
-
self.response_encoding ||= "base64"
-
end
-
-
def order_exists
-
self.certificate_order=CertificateOrder.find_by_ref(self.ref)
-
errors[:ref] << "doesn't exist'" unless self.certificate_order
-
end
-
-
end
-
class ApiCertificateRevoke < ApiCertificateRequest
-
validates :account_key, :secret_key, :reason, presence: true
-
validates :ref, presence: true
-
-
# return values
-
attr_accessor :status
-
-
end
-
1
class ApiCredential < ActiveRecord::Base
-
1
belongs_to :ssl_account
-
-
1
validates :account_key, :secret_key, presence: true, length: {minimum: 6}
-
# validates :ssl_account, presence: true, on: :create
-
-
1
after_initialize do
-
99
if new_record?
-
99
self.account_key ||= SecureRandom.hex(6)
-
99
self.secret_key ||= SecureRandom.base64(10)
-
end
-
end
-
-
1
def reset_secret_key
-
update_attribute :secret_key, SecureRandom.base64(10)
-
end
-
-
1
def set_role_ids role_ids
-
self.roles = role_ids.to_json
-
end
-
-
1
def role_ids
-
self.roles.nil? ? nil : (JSON.parse self.roles)
-
end
-
-
1
def role_names
-
role_names = []
-
unless role_ids.nil?
-
role_ids.each do |role_id|
-
role_names << Role.find(role_id).name
-
end
-
end
-
role_names
-
end
-
end
-
class ApiCreditCard
-
include ActiveModel::Validations
-
include ActiveModel::Serialization
-
-
# attr_accessor :first_name, :last_name, :number, :expires, :cvv, :street_address_1,
-
# :street_address_2, :street_address_3, :post_office_box, :locality, :state_or_province, :postal_code, :country
-
#
-
validates_presence_of :first_name, :last_name, :number, :expires, :cvv, :street_address_1, :locality,
-
:state_or_province, :postal_code, :country
-
-
attr_accessor :attributes
-
def initialize(attributes = {})
-
@attributes = attributes
-
end
-
-
def read_attribute_for_validation(key)
-
@attributes[key]
-
end
-
end
-
class ApiDcvEmailResend < ApiCertificateRequest
-
validates :account_key, :secret_key, :ref, presence: true
-
validates :email_address, email: true, unless: lambda{|c|c.email_address.blank?}
-
validates_presence_of :order_exists, :verify_dcv_email_address, on: :create
-
-
attr_accessor :certificate_order, :sent_at
-
-
def order_exists
-
errors[:email_address]<< "certificate order #{ref} does not exist" unless
-
certificate_order=CertificateOrder.find_by_ref(ref)
-
end
-
-
-
def verify_dcv_email_address
-
if self.email_address
-
emails=ComodoApi.domain_control_email_choices(certificate_order.common_name).email_address_choices
-
errors[:email_address]<< "must be one of the following: #{emails.join(", ")}" unless
-
emails.include?(self.dcv_email_address)
-
end
-
end
-
-
end
-
class ApiDcvEmails < ApiCertificateRequest
-
validates :account_key, :secret_key, presence: true
-
validates :domains, domain_name: true, unless: "domains.blank?"
-
validates :domain, domain_name: true, unless: "domain.blank?"
-
validates :domain, presence: true, if: "domains.blank?"
-
-
attr_accessor :email_addresses
-
-
end
-
class ApiDcvMethods < ApiCertificateRequest
-
validates :account_key, :secret_key, presence: true
-
validates :csr, presence: true, if: lambda{|c|c.ref.blank?}
-
-
attr_accessor :dcv_methods, :instructions, :md5_hash, :sha1_hash, :sha2_hash, :dns_sha2_hash, :dns_md5_hash, :ca_tag
-
-
INSTRUCTIONS="https://#{Settings.portal_domain}/faqs/ssl-dv-validation-requirements/"
-
end
-
require "declarative_authorization/maintenance"
-
-
class ApiManagedCertificateCreate < ApiSslManagerRequest
-
attr_accessor :status
-
-
validates :account_key, :secret_key, presence: true
-
validates :certificates, presence: true
-
-
def create_managed_certificates
-
registered_agent = RegisteredAgent.find_by_ref(self.ref)
-
-
self.certificates.each do |cert|
-
managed_certificate = ManagedCertificate.new
-
managed_certificate.body = cert
-
managed_certificate.type = 'ManagedCertificate'
-
managed_certificate.registered_agent = registered_agent
-
managed_certificate.status = managed_certificate.expired? ? "expired" : "valid"
-
managed_certificate.save!
-
end
-
-
registered_agent.api_status = 'registered'
-
registered_agent
-
end
-
end
-
require "declarative_authorization/maintenance"
-
-
class ApiManagedCertificateRetrieve < ApiSslManagerRequest
-
validates :account_key, :secret_key, presence: true
-
end
-
class ApiParameters < ApiCertificateRequest
-
validates :account_key, :secret_key, presence: true
-
validates :api_call, presence: true
-
-
attr_accessor :parameters
-
-
end
-
class ApiSignedCertificateRequest < ApiCertificateRequest
-
validates :account_key, :secret_key, presence: true
-
validates :pub_key, presence: true
-
end
-
require "declarative_authorization/maintenance"
-
-
class ApiSslManagerCreate < ApiSslManagerRequest
-
attr_accessor :status, :reason
-
-
validates :account_key, :secret_key, presence: true
-
validates :ip_address, :mac_address, :agent, presence: true
-
-
def create_ssl_manager
-
already_registered = RegisteredAgent.where(
-
ip_address: self.ip_address,
-
mac_address: self.mac_address,
-
agent: self.agent
-
).first
-
-
if already_registered
-
already_registered.api_status = 'already_registered' if already_registered.workflow_status == "active"
-
already_registered.api_status = 'pending' if already_registered.workflow_status == "pending_registration"
-
-
return already_registered
-
else
-
@registered_agent = RegisteredAgent.new
-
-
@registered_agent.ip_address = self.ip_address
-
@registered_agent.mac_address = self.mac_address
-
@registered_agent.agent = self.agent
-
@registered_agent.friendly_name = self.friendly_name ? self.friendly_name : self.mac_address
-
@registered_agent.ssl_account = api_requestable
-
@registered_agent.requester = User.find_by_login(self.requester)
-
@registered_agent.requested_at = DateTime.now
-
@registered_agent.approver = @registered_agent.requester if Settings.auto_approve_ssl_manager_register
-
@registered_agent.approved_at = @registered_agent.requested_at if Settings.auto_approve_ssl_manager_register
-
@registered_agent.workflow_status = Settings.auto_approve_ssl_manager_register ? 'active' : 'pending_registration'
-
-
if @registered_agent.save
-
Assignment.where(
-
ssl_account_id: api_requestable.id,
-
role_id: Role.get_role_id([Role::OWNER, Role::ACCOUNT_ADMIN])).map(&:user).uniq.compact.each do |user|
-
user.deliver_register_ssl_manager_to_team!(
-
@registered_agent.ref,
-
api_requestable,
-
Settings.auto_approve_ssl_manager_register
-
)
-
end
-
end
-
-
@registered_agent.api_status = Settings.auto_approve_ssl_manager_register ? 'approved' : 'pending'
-
-
return @registered_agent
-
end
-
end
-
end
-
require "declarative_authorization/maintenance"
-
-
class ApiSslManagerDelete < ApiSslManagerRequest
-
attr_accessor :status
-
-
validates :account_key, :secret_key, presence: true
-
validates :ref_list, presence: true
-
-
def delete_ssl_manager
-
failed_ref_list = []
-
status = ""
-
-
self.ref_list.each do |ref|
-
registered_agent = api_requestable.registered_agents.find_by_ref(ref)
-
destroyed = registered_agent.destroy if registered_agent
-
failed_ref_list << ref unless destroyed
-
end
-
-
if failed_ref_list.size == 0
-
status = "Successfully deleted SSL Managers."
-
else
-
status = "It has been failed to delete SSL Manager(s) what ref is in '" +
-
failed_ref_list.join(', ') +
-
"'. Please try again to delete those SSL Manager(s)."
-
end
-
-
status
-
end
-
end
-
class ApiSslManagerRequest < CaApiRequest
-
attr_accessor :test, :action
-
-
REGISTER = [:ref, :ip_address, :mac_address, :agent, :friendly_name, :workflow_status, :account_key,
-
:secret_key, :requester]
-
COLLECTION = [:certificates]
-
COLLECTIONS = [:common_name, :subject_alternative_names, :effective_date, :expiration_date, :serial, :issuer, :status]
-
DELETE = [:ref_list]
-
-
attr_accessor *(REGISTER+DELETE+COLLECTION+COLLECTIONS).uniq
-
-
before_validation(on: :create) do
-
ac = api_credential
-
-
unless ac.blank?
-
self.api_requestable = ac.ssl_account
-
else
-
errors[:login] << "account_key not found or wrong secret_key"
-
false
-
end
-
end
-
-
def api_credential
-
(self.account_key && self.secret_key) ?
-
ApiCredential.find_by_account_key_and_secret_key(self.account_key, self.secret_key) : nil
-
end
-
-
def find_ssl_managers(search)
-
ssl_managers = self.api_requestable.registered_agents
-
ssl_managers = ssl_managers.search_with_terms(search) if search
-
-
if ssl_managers
-
ssl_managers
-
else
-
(errors[:ssl_managers] << "SSL Managers not found.")
-
end
-
end
-
-
def find_managed_certs(ssl_manager_ref, search)
-
ssl_manager = self.api_requestable.registered_agents.find_by_ref(ssl_manager_ref)
-
-
if ssl_manager
-
managed_certs = search ? ssl_manager.managed_certificates.search_with_terms(search) : ssl_manager.managed_certificates
-
if managed_certs
-
managed_certs
-
else
-
(errors[:managed_certificates] << ("Managed Certificates not found for SSL Manager #" + ssl_manager_ref))
-
end
-
else
-
(errors[:ssl_manager] << "SSL Manager not found.")
-
end
-
end
-
end
-
require "declarative_authorization/maintenance"
-
-
class ApiSslManagerRetrieve < ApiSslManagerRequest
-
validates :account_key, :secret_key, presence: true
-
end
-
require "declarative_authorization/maintenance"
-
-
class ApiUserCreate_v1_4 < ApiUserRequest
-
attr_accessor :user_url, :api_request, :api_response, :error_code, :error_message, :status
-
-
validates :login, :email, :password, presence: true
-
validates :email, email: true
-
validates :password, length: { in: 6..20 }
-
-
def create_user
-
params = {
-
login: self.login,
-
email: self.email,
-
password: self.password,
-
password_confirmation: self.password,
-
persist_notice: true
-
}
-
@user = User.create(params)
-
if @user.errors.empty?
-
@user.create_ssl_account([Role.get_owner_id])
-
@user.signup!({user: params})
-
@user.activate!({user: params})
-
-
# Check Code Signing Certificate Order for assign as assignee.
-
CertificateOrder.unscoped.search_validated_not_assigned(@user.email).each do |cert_order|
-
cert_order.update_attribute(:assignee, @user)
-
LockedRecipient.create_for_co(cert_order)
-
end
-
-
@user.deliver_activation_confirmation!
-
@user_session = UserSession.create(@user)
-
@current_user_session = @user_session
-
Authorization.current_user = @current_user = @user_session.record
-
end
-
@user
-
end
-
end
-
class ApiUserListTeam_v1_4 < ApiUserRequest
-
attr_accessor :acct_number, :api_request, :api_response, :error_code, :error_message, :company_name, :roles, :created_at, :updated_at, :status, :ssl_slug, :issue_dv_no_validation, :billing_method,:available_funds, :currency, :reseller_tier, :is_default_team
-
-
validates :login, :password, presence: true
-
validates :company_name, length: {in: 2..20}, allow_nil: true
-
-
end
-
class ApiUserRequest < CaApiRequest
-
attr_accessor :test, :action, :admin_submitted
-
-
CREATE_ACCESSORS_1_4 = [:login, :email, :password, :first_name, :last_name, :phone, :organization, :address1,
-
:address2, :address3, :po_box, :postal_code, :city, :state, :country, :account_key,
-
:secret_key, :options, :account_number]
-
-
attr_accessor *(CREATE_ACCESSORS_1_4).uniq
-
-
before_validation(on: :create) do
-
if self.account_key && self.secret_key
-
ac=ApiCredential.find_by_account_key_and_secret_key(self.account_key, self.secret_key)
-
unless ac.blank?
-
self.api_requestable = ac.ssl_account
-
else
-
errors[:login] << "account_key not found or wrong secret_key"
-
end
-
end
-
end
-
-
def find_user
-
if defined?(:login) && self.login
-
if self.api_requestable.users.find(&:is_admin?)
-
self.admin_submitted = true
-
if user=User.find_by_login(self.login)
-
self.api_requestable = user.ssl_account
-
user
-
else
-
errors[:user] << "User account not found for '#{self.login}'."
-
end
-
else
-
self.api_requestable.certificate_orders.find_by_ref(self.ref) || (errors[:certificate_order] << "Certificate order not found for ref #{self.ref}.")
-
end
-
end
-
end
-
-
def login
-
read_attribute(:login) || JSON.parse(self.parameters)["login"]
-
end
-
-
def retry
-
%x"curl -k -H 'Accept: application/json' -H 'Content-type: application/json' -X #{request_method.upcase} -d '#{parameters}' #{request_url.gsub(".com",".local:3000").gsub("http:","https:")}"
-
end
-
end
-
class ApiUserSetDefaultTeam_v1_4 < ApiUserRequest
-
attr_accessor :api_request, :api_response, :error_code, :error_message, :success_message, :acct_number
-
-
validates :login, :password, presence: true
-
-
end
-
class ApiUserShow_v1_4 < ApiUserRequest
-
attr_accessor :user_url, :api_request, :api_response, :error_code, :error_message, :status, :available_funds
-
-
validates :login, :password, presence: true
-
validates :password, length: { in: 6..20 }
-
-
end
-
class AppRep < Contact
-
-
belongs_to :ssl_account
-
-
CALLBACK_METHODS=['t','l']
-
validates :callback_method,
-
inclusion: {in: CALLBACK_METHODS,
-
message: "needs to one of the following: #{CALLBACK_METHODS}"}
-
validate :phone, if: lambda{|a|a.callback_method=='t'}
-
end
-
1
class Assignment < ActiveRecord::Base
-
1
belongs_to :user, touch: true
-
1
belongs_to :role
-
1
belongs_to :ssl_account, touch: true
-
-
1
def self.users_can_manage_invoice(team)
-
if team && team.is_a?(SslAccount)
-
Assignment.where(
-
ssl_account_id: team.id, role_id: Role.can_manage_payable_invoice
-
).map(&:user).uniq
-
else
-
[]
-
end
-
end
-
end
-
class Authentication < ActiveRecord::Base
-
belongs_to :user
-
validates :user_id, :uid, :provider, :presence => true
-
validates_uniqueness_of :uid, :scope => :provider
-
end
-
class BillingContact < CertificateContact
-
end
-
1
class BillingProfile < ActiveRecord::Base
-
1
include ActiveMerchant::Billing::CreditCardMethods
-
-
1
belongs_to :ssl_account
-
1
has_many :orders, -> { unscope(where: [:state]) }
-
-
1
before_create :store_last_digits
-
1
after_save :set_one_default
-
-
1
cattr_accessor :password
-
1
attr_accessor :number, :stripe_card_token
-
1
attr_encrypted :card_number, :key => 'v1X&3az00c!F',algorithm: 'aes-256-cbc', :mode => :per_attribute_iv_and_salt,
-
insecure_mode: true
-
-
1
ALL_COLUMNS = %w(description first_name last_name company address_1 address_2
-
postal_code city state country phone vat credit_card card_number
-
expiration_month expiration_year security_code last_digits data salt notes
-
created_at updated_at)
-
1
EXCLUDED_COLUMNS = %w(created_at updated_at description notes last_digits data salt)
-
1
EXTENDED_FIELDS = %w(address_1 address_2)
-
1
CREDIT_CARD_COLUMNS = %w(credit_card card_number security_code expiration_year expiration_month)
-
1
BILLING_INFORMATION_COLUMNS = ALL_COLUMNS - EXCLUDED_COLUMNS - CREDIT_CARD_COLUMNS
-
1
REQUIRED_COLUMNS = BILLING_INFORMATION_COLUMNS + CREDIT_CARD_COLUMNS - %w{address_2 company vat}
-
1
TOP_COUNTRIES = ["United States", "United Kingdom", "Canada"]
-
1
CREDIT_CARDS = ["Visa", "Master Card", "Discover", "American Express"]
-
1
AMERICAN = "United States"
-
-
1
GATEWAY = ENV['GATEWAY']
-
# test - see http://developer.authorize.net/tools/errorgenerationguide/
-
# TEST_ZIP_CODE = 46204 #46282 #decline
-
1
TEST_AMOUNT = 80.50 # valid
-
# TEST_AMOUNT = 70.02 # This transaction has been declined.
-
-
1
validates_presence_of *((REQUIRED_COLUMNS).map(&:intern))
-
-
1
default_scope{ where{(status << ['disable']) | (status == nil)}}
-
-
1
scope :success, lambda{
-
joins{orders.transactions}.where{orders.transactions.success==true}
-
}
-
-
1
scope :search, lambda {|term|
-
joins{orders}.where{(first_name =~ "%#{term}%") |
-
(last_name =~ "%#{term}%") |
-
(address_1 =~ "%#{term}%") |
-
(address_2 =~ "%#{term}%") |
-
(country =~ "%#{term}%") |
-
(city =~ "%#{term}%") |
-
(state =~ "%#{term}%") |
-
(postal_code =~ "%#{term}%") |
-
(phone =~ "%#{term}%") |
-
(company =~ "%#{term}%") |
-
(last_digits =~ "%#{term}%") |
-
(orders.reference_number =~ "%#{term}%")}
-
}
-
-
1
def verification_value?() false end
-
-
1
def to_xml(options = {})
-
super options.merge(:except => [:data, :salt])
-
end
-
-
1
def full_name
-
first_name + " " + last_name
-
end
-
-
1
def masked_card_number
-
card = card_number.gsub(/\s+/, '')
-
mask = (0..(card.size - 8)).inject('') {|array,n|array << '*'}
-
card.gsub(/(?<=\d{4})\d+(?=\d{4})/, mask)
-
end
-
-
1
def build_credit_card(options={})
-
options.reverse_merge! cvv: true
-
cc={ :first_name => options[:first_name] || first_name,
-
:last_name => options[:last_name] || last_name,
-
:number => options[:card_number] || card_number,
-
:month => options[:expiration_month] || expiration_month,
-
:year => options[:expiration_year] || expiration_year}
-
cc.merge!(:verification_value => options[:verification_value] || security_code) if options[:cvv]
-
card = ActiveMerchant::Billing::CreditCard.new(cc)
-
card.brand = 'bogus' if defined?(::GATEWAY_TEST_CODE)
-
card
-
end
-
-
1
def build_address
-
Address.new({
-
:name => self.full_name,
-
:street1 => self.address_1,
-
:street2 => self.address_2,
-
:locality => self.city,
-
:region => self.state,
-
:country => self.country,
-
:postal_code => (%w{development test}.include?(Rails.env) && defined?(TEST_ZIP_CODE)) ? TEST_ZIP_CODE : self.postal_code, #testing decline or not
-
:phone => self.phone
-
})
-
end
-
-
1
def build_info(description)
-
{billing_address: self.build_address, description: description}
-
end
-
-
1
def american?
-
country == AMERICAN
-
end
-
-
1
def expired?
-
Date.new(expiration_year,expiration_month).end_of_month < Date.today
-
end
-
-
#if credit card is expired, provide two theoretical dates - incremented by 2 and 3 respectively
-
1
def cycled_years
-
unless expired?
-
[expiration_year]
-
else
-
diff=((DateTime.now.to_i - DateTime.new(expiration_year, expiration_month).to_i)/1.year)
-
[2,3].map do |i|
-
v=diff/i
-
#any reminders?
-
expiration_year+((v.to_i + (v.is_a?(Integer) ? o : 1))*i)
-
end
-
end
-
end
-
-
1
def self.nullify_card_number_field
-
self.find_each{|bp|bp.update_column(:card_number, nil)}
-
end
-
-
1
def self.encrypt_all_card_numbers
-
self.find_each{|bp|bp.update_attribute(:card_number, bp.read_attribute(:card_number)) if
-
bp.encrypted_card_number.blank?}
-
end
-
-
1
def self.gateway_stripe?
-
1
GATEWAY == 'stripe'
-
end
-
-
1
def self.anet_public_keys
-
# public keys that can be displayed and used with Authorize.net Accept.js
-
{
-
client_key: Rails.application.secrets.authorize_net_client_key,
-
api_login_id: Rails.application.secrets.authorize_net_key
-
}
-
end
-
-
1
def users_can_manage
-
Assignment.where(
-
ssl_account_id: ssl_account.id, role_id: Role.can_manage_billing
-
).map(&:user).uniq
-
end
-
-
1
private
-
-
1
def default_profile_exists?
-
ssl_account.billing_profiles.where(default_profile: true).any?
-
end
-
-
1
def set_one_default
-
if default_profile
-
ssl_account.billing_profiles
-
.where(default_profile: true).where.not(id: id)
-
.update_all(default_profile: false)
-
else
-
unless default_profile_exists?
-
self.update(default_profile: true)
-
end
-
end
-
end
-
-
1
def store_last_digits
-
self.last_digits = self.class.last_digits(card_number)
-
end
-
-
1
def validate
-
errors.add(:expiration_year, "is invalid" ) unless valid_expiry_year?(expiration_year)
-
errors.add(:expiration_month, "is invalid" ) unless valid_month?(expiration_month)
-
errors.add(:card_number, "is invalid" ) unless self.class.valid_number?(card_number)
-
if password.blank?
-
errors[:base] << "Unable to encrypt or decrypt data without password"
-
end
-
end
-
end
-
class BillingProfileUnscoped < BillingProfile
-
self.default_scopes = []
-
end
-
class Blacklist < Blocklist
-
end
-
class Blocklist < ActiveRecord::Base
-
end
-
class Ca < ActiveRecord::Base
-
-
has_many :cas_certificates, dependent: :destroy
-
has_many :certificates, through: :cas_certificates
-
serialize :caa_issuers
-
serialize :ekus
-
-
scope :ssl_account, ->(ssl_account){joins{cas_certificates}.where{cas_certificates.ssl_account_id==ssl_account.id}.uniq} #private PKI
-
scope :ssl_account_or_general, ->(ssl_account){
-
(ssl_account(ssl_account).empty? ? general : ssl_account(ssl_account))}
-
scope :ssl_account_or_general_default, ->(ssl_account){
-
ssl_account_or_general(ssl_account).default}
-
scope :ssl_account_or_general_shadow, ->(ssl_account){
-
ssl_account_or_general(ssl_account).shadow}
-
scope :general, ->{where{cas_certificates.ssl_account_id==nil}} # Cas not assigned to any team (Public PKI)
-
scope :default, ->{where{cas_certificates.status==CasCertificate::STATUS[:default]}.uniq}
-
scope :shadow, ->{where{cas_certificates.status==CasCertificate::STATUS[:shadow]}.uniq}
-
-
# Root CAs - determines the certificate chain used
-
CERTLOCK_CA = "certlock"
-
ECOSSL_CA = "ecossl"
-
SSLCOM_CA = "sslcom"
-
MANAGEMENT_CA = "management_ca"
-
-
EKUS = {server: "tls",
-
client: "client",
-
email: "smime",
-
time_stamping: "ts",
-
code_signing: "cs"}
-
-
END_ENTITY = {
-
evcs: 'EV_CS_CERT_EE',
-
cs: 'CS_CERT_EE',
-
ov_client: 'OV_CLIENTAUTH_CERT_EE',
-
dvssl: 'DV_SERVER_CERT_EE',
-
ovssl: 'OV_SERVER_CERT_EE',
-
evssl: 'EV_SERVER_CERT_EE'
-
}
-
-
# issuer (entity and purpose)
-
ISSUER = {sslcom_shadow: 1}
-
SSL_ACCOUNT_MAPPING = {"a30-1e3mjj3" =>
-
{"SSLcom-SubCA-SSL-RSA-4096-R1" => "DTNT-Intermediate-SSL-RSA-4096-R2",
-
"SSLcom-SubCA-CodeSigning-RSA-4096-R1" => "DTNT-Intermediate-codeSigning-RSA-4096-R2",
-
"SSLcom-SubCA-EV-SSL-RSA-4096-R3" => "DTNT-Intermediate-EV-SSL-RSA-4096-R2"},
-
"ade-1e41it0" =>
-
{"SSLcom-SubCA-SSL-RSA-4096-R1" => "MilleniumSign-Intermediate-SSL-RSA-4096-R2",
-
"SSLcom-SubCA-SSL-ECC-384-R2" => "MilleniumSign-Intermediate-SSL-ECC-384-R2",
-
"SSLcom-SubCA-CodeSigning-RSA-4096-R1" => "MilleniumSign-Intermediate-codeSigning-RSA-4096-R3",
-
"SSLcom-SubCA-clientCert-RSA-4096-R2" => "MilleniumSign-Intermediate-clientCert-RSA-4096-R3",
-
"SSLcom-SubCA-clientCert-ECC-384-R2" => "MilleniumSign-Intermediate-clientCert-ECC-384-R3",
-
"SSLcom-SubCA-EV-SSL-RSA-4096-R3" => "MilleniumSign-Intermediate-EV-SSL-RSA-4096-R3"},
-
"aef-1epq21m" => # SafeToOpen
-
{"SSLcom-SubCA-SSL-RSA-4096-R1" => "SafeToOpen-SSL-SubCA-RSA-4096-R1",
-
# "SSLcom-SubCA-SSL-ECC-384-R2" => "SafeToOpen-SSL-SubCA-ECC-384-R1",
-
"SSLcom-SubCA-CodeSigning-RSA-4096-R1" => "SafeToOpen-codeSigning-SubCA-RSA-4096-R1",
-
"SSLcom-SubCA-clientCert-RSA-4096-R2" => "SafeToOpen-clientCert-SubCA-RSA-4096-R1",
-
# "SSLcom-SubCA-clientCert-ECC-384-R2" => "SafeToOpen-clientCert-SubCA-ECC-384-R1",
-
"SSLcom-SubCA-EV-SSL-RSA-4096-R3" => "SafeToOpen-EV-SSL-SubCA-RSA-4096-R1"},
-
"af7-1epf2p9" => # DodoSign
-
{"SSLcom-SubCA-SSL-RSA-4096-R1" => "DodoSign-Intermediate-SSL-RSA-4096-R1",
-
"SSLcom-SubCA-SSL-ECC-384-R2" => "DodoSign-Intermediate-SSL-ECC-384-R1",
-
"SSLcom-SubCA-CodeSigning-RSA-4096-R1" => "DodoSign-Intermediate-codeSigning-RSA-4096-R1",
-
"SSLcom-SubCA-clientCert-RSA-4096-R2" => "DodoSign-Intermediate-clientCert-RSA-4096-R1",
-
"SSLcom-SubCA-clientCert-ECC-384-R2" => "DodoSign-Intermediate-clientCert-ECC-384-R1",
-
"SSLcom-SubCA-EV-SSL-RSA-4096-R3" => "DodoSign-Intermediate-EV-SSL-RSA-4096-R1"}}
-
-
validates :ref, presence: true, uniqueness: true
-
-
def ecc_profile
-
Ca.find_by(end_entity: end_entity, description: description, algorithm: "ecc" )
-
end
-
-
def downstep
-
down_profile,down_entity=
-
case profile_name
-
when /\AEV/
-
[profile_name,end_entity].map{|field|field.gsub "EV","DV"}
-
when /\AOV/
-
[profile_name,end_entity].map{|field|field.gsub "OV","DV"}
-
end
-
Ca.find_by(profile_name: down_profile, host: host, end_entity: down_entity)
-
end
-
-
def is_ev?
-
profile_name=~/EV/
-
end
-
-
private
-
-
end
-
class CaApiRequest < ActiveRecord::Base
-
belongs_to :api_requestable, polymorphic: true
-
-
default_scope{ order("created_at desc")}
-
-
def success?
-
Rails.cache.fetch("#{cache_key}/success", expires_in: 24.hours) do
-
!!(response=~/errorCode=0/ or response=~/\A0\n/)
-
end
-
end
-
-
def parameters_to_hash
-
Rails.cache.fetch("#{cache_key}/parameters_to_hash", expires_in: 24.hours) do
-
JSON.parse self.parameters
-
end
-
end
-
-
def redacted_parameters
-
Rails.cache.fetch("#{cache_key}/redacted_parameters", expires_in: 24.hours) do
-
parameters.gsub(/(&loginName=).+?(&loginPassword=).+/, '\1[REDACTED]\2[REDACTED]')
-
end
-
end
-
end
-
# This class represent requests sent to the CA (ie Comodo or the SSL.com Root CA)
-
-
class CaCertificateRequest < CaApiRequest
-
-
def order_number
-
m=response.match(/(?<=orderNumber=)(.+?)&/)
-
m[1] unless m.blank?
-
end
-
-
def certificate_id
-
m=response.match(/(?<=certificateID=)(.+?)&/)
-
m[1] unless m.blank?
-
end
-
-
def total_cost
-
m=response.match(/(?<=totalCost=)(.+?)&/)
-
m[1].to_f unless m.blank?
-
end
-
-
def response_to_hash
-
CGI::parse(response)
-
end
-
-
def response_value(key=nil)
-
codes = response_to_hash
-
key.blank? ? codes : (codes[key].blank? ? "" : codes[key][0])
-
end
-
-
def unique_value
-
response_value("uniqueValue").blank? ? (response =~ /.+?\n.+?\n(.+)?\n/ ; $1) : response_value("uniqueValue")
-
end
-
-
def response_error_code
-
codes = response_to_hash
-
codes['errorCode'].blank? ? "" : codes['errorCode'][0]
-
end
-
-
def response_unique_value
-
codes = response_to_hash
-
codes['uniqueValue'].blank? ? "" : codes['uniqueValue'][0]
-
end
-
-
def response_error_message
-
codes = response_to_hash
-
codes['errorMessage'].blank? ? "" : codes['errorMessage'][0].gsub(/comodo/i,'SSL.com').gsub(/\!AutoApplySSL/,'api access')
-
end
-
-
def response_certificate_eta
-
codes = response_to_hash
-
codes['expectedDeliveryTime'] ? codes['expectedDeliveryTime'][0] : ""
-
end
-
-
def response_certificate_status
-
codes = response_to_hash
-
codes['certificateStatus'] ? codes['certificateStatus'][0] : ""
-
end
-
-
-
end
-
class CaDcvRequest < CaApiRequest
-
-
def success?
-
!!(response=~/^0\n/)
-
end
-
-
["domain_name", "whois_email", "level2_email", "level3_email", "level4_email", "level5_email"].each do |i|
-
define_method "#{i}" do
-
choices = parse_email_choices
-
choices.shift #remove status
-
choices = Hash[*choices.reverse]
-
choices.select{|k,v|v=="#{i}"}.map{|k,v|k}
-
end
-
end
-
-
def email_address_choices
-
success? ? whois_email+level2_email+level3_email+level4_email+level5_email : []
-
end
-
-
private
-
-
def parse_email_choices
-
response.split(/[\n|\t]/)
-
end
-
end
-
class CaDcvResendRequest < CaApiRequest
-
-
end
-
class CaMdcStatus < CaApiRequest
-
-
def response_code
-
response =~ /\A(\d)\n/
-
$1.to_i
-
end
-
-
def domain_status
-
vals=response.split("&").select{|v|v=~/\d+_/}.map{|s|s.split("=")}.transpose
-
unless vals.blank?
-
ki, vi, status=1, 0, {}
-
(vals[0].count/3).times do |v|
-
status.merge!({vals[1][vi]=>{"method"=>vals[1][vi+1].gsub("+"," "),"status"=>vals[1][vi+2].gsub("+"," ")}})
-
vi+=3
-
end
-
status
-
end
-
end
-
-
def status
-
response =~ /.+\n(.+?)\Z/m
-
$1
-
end
-
-
end
-
class CaRetrieveCertificate < CaApiRequest
-
-
def response_code
-
response =~ /\A(\-?\d+)/
-
$1.to_i
-
end
-
-
#format is as follows - response_code, cert, status
-
def certificate
-
response =~ /\A\d\n(.+)\n\n.+?/m if response_code==2
-
$1
-
end
-
-
def status
-
response =~ /.+\n(.+?)\Z/m
-
$1
-
end
-
-
end
-
class CaRevokeCertificate < CaApiRequest
-
-
def response_code
-
response =~ /\A(\d)\n/
-
$1.to_i
-
end
-
-
#format is as follows - response_code, cert, status
-
def certificate
-
response =~ /\A\d\n(.+)\n.+?/m if response_code==2
-
$1
-
end
-
-
def status
-
response =~ /.+\n(.+?)\Z/m
-
$1
-
end
-
-
end
-
class CaaCheck < ActiveRecord::Base
-
belongs_to :checkable, :polymorphic => true
-
-
CAA_COMMAND=->(name, authority){
-
%x{echo `cd #{Rails.application.secrets.caa_check_path} && python checkcaa.py #{name} #{authority}`}
-
}
-
-
CaaCheckJob = Struct.new(:certificate_order_id, :certificate_name, :certificate_content) do
-
def perform
-
name = certificate_name.name
-
is_comodoca = certificate_content.nil? ? false : (certificate_content.ca.nil? ? false : true)
-
-
if is_comodoca
-
result = caa_lookup(name, "comodoca.com")
-
if result == true # Timeout
-
return_obj = true
-
elsif result =~ /status/ # Returned CAA Check Result.
-
arry = JSON.parse(result.gsub("}\n", "}").gsub("\n", "|||"))
-
log_caa_check(certificate_order_id, name, 'comodoca.com', arry)
-
-
if arry['status'].to_s == 'true'
-
return_obj = true
-
elsif arry['status'].to_s == 'false'
-
if arry['caatestout'].include? 'Failed to send CAA query to'
-
return_obj = true
-
elsif arry['caatestout'].include? 'not present in issue tag'
-
return_obj = false
-
end
-
end
-
else
-
return_obj = false
-
end
-
else
-
result = caa_lookup(name, "ssl.com")
-
if result == true # Timeout
-
return_obj = true
-
elsif result =~ /status/ # Returned CAA Check Result.
-
arry = JSON.parse(result.gsub("}\n", "}").gsub("\n", "|||"))
-
log_caa_check(certificate_order_id, name, 'ssl.com', arry)
-
-
if arry['status'].to_s == 'true'
-
return_obj = true
-
elsif arry['status'].to_s == 'false'
-
if arry['caatestout'].include? 'Failed to send CAA query to'
-
return_obj = true
-
elsif arry['caatestout'].include? 'not present in issue tag'
-
return_obj = false
-
end
-
end
-
else
-
return_obj = false
-
end
-
end
-
-
certificate_name.update_attribute(:caa_passed, return_obj)
-
end
-
-
def caa_lookup(name, authority)
-
begin
-
@checkcaa=IO.popen("echo `cd #{Rails.application.secrets.caa_check_path} && python checkcaa.py #{name} #{authority}`")
-
result = @checkcaa.read
-
Process.wait @checkcaa.pid
-
result
-
rescue RuntimeError
-
return false
-
rescue Exception=>e
-
return false
-
end
-
end
-
-
def log_caa_check(cert_order_ref, name, authority, result)
-
dir = Rails.application.secrets.caa_check_log_path
-
Dir.mkdir(dir) unless Dir.exists?(dir)
-
-
caatestout = result['caatestout'].gsub("|||", "\n")
-
message = result['message'].gsub("|||", "\n")
-
-
log_path = (dir + '/' + cert_order_ref + '.txt').gsub('//', '/')
-
file = File.open(log_path, 'a')
-
file.write "**************************************** " + authority + " **************************************** \n"
-
file.write "CAA " + authority + " check results for domain \"" + name + "\" at " + Time.now.strftime("%d/%m/%Y %H:%M:%S") + "\n"
-
file.write "CAA " + authority + " test out : \n"
-
file.write (caatestout + "\n").gsub("\n\n", "\n")
-
file.write "Message : \n"
-
file.write (message + "\n").gsub("\n\n", "\n")
-
file.write "\n"
-
file.close
-
end
-
end
-
-
def self.pass?(certificate_order_id, certificate_name, certificate_content)
-
true # Delayed::Job.enqueue CaaCheckJob.new(certificate_order_id, certificate_name, certificate_content)
-
end
-
end
-
class CasCertificate < ActiveRecord::Base
-
STATUS = {default: "default",
-
active: "active",
-
inactive: "inactive",
-
shadow: "shadow",
-
hide: "hide"}
-
-
GENERAL_DEFAULT_CACHE="general_default_cache"
-
-
belongs_to :ca
-
belongs_to :certificate
-
belongs_to :ssl_account, touch: true
-
-
scope :ssl_account, ->(ssl_account){where{ssl_account_id==ssl_account.id}.uniq}
-
scope :ssl_account_or_general_default, ->(ssl_account){
-
(ssl_account(ssl_account).empty? ? general : ssl_account(ssl_account)).default}
-
scope :general, ->{where{ssl_account_id==nil}.uniq}
-
scope :default, ->{where{status==STATUS[:default]}.uniq}
-
scope :shadow, ->{where{status==STATUS[:shadow]}.uniq}
-
end
-
-
-
-
1
class Cdn < ActiveRecord::Base
-
1
belongs_to :ssl_account
-
1
belongs_to :certificate_order
-
-
#will_paginate
-
1
cattr_accessor :per_page
-
1
@@per_page = 10
-
end
-
class CertUtil
-
CONVERT_PKCS7_TO_PEM=->(pem, pkcs7){%x"openssl pkcs7 -print_certs -in #{pkcs7} -out #{pem}"}
-
CONVERT_PEM_TO_PKCS7=->(pem, pkcs7, chain){%x"openssl crl2pkcs7 -nocrl -certfile #{pem} -out #{pkcs7} -certfile #{chain}"}
-
DECODE_CERTIFICATE=->(cert_file, format){%x"openssl #{format} -in #{cert_file} -text -noout #{'-print_certs' if format=='pkcs7'}"}
-
CONNECT_HTTPS=->(host, port="443", protocol="tls1_2"){%x"openssl s_client -servername #{host} -connect #{host}:#{port} -#{protocol}"}
-
-
def self.pkcs7_to_pem(pem, out)
-
CONVERT_PKCS7_TO_PEM.call pem, out
-
end
-
-
def self.pem_to_pkcs7(pem, chain, out)
-
CONVERT_PEM_TO_PKCS7.call pem, out, chain
-
end
-
-
def self.decode_certificate(cert_file,format)
-
DECODE_CERTIFICATE.call cert_file,format
-
end
-
-
-
# openssl pkcs7 -in orig_pkcs7.cer -out all_x509.pem -print_certs (where
-
# orig_pkcs7.cer is your original pkcs7 cert and all_x509.pem are all the
-
# resulting x509 certs)
-
#
-
# to convert a pkcs7 to it's x509 components, and then converting those
-
# x509 certs back into a pkcs7 file using:
-
#
-
# openssl crl2pkcs7 -nocrl -certfile certificate.cer -out new_pkcs7.cer
-
# -certfile x509_chain.pem (where new_pkcs7.cer is the new pkcs7 cert which
-
# should match the original you sent us, x509_chain.pem are the intermediate
-
# certs copied from all_x509.pem and certificate.cer is the certificate file
-
# copied from all_x509.pem)
-
end
-
class Certificate < ActiveRecord::Base
-
extend Memoist
-
include CertificateType
-
include PriceView
-
include Filterable
-
include Sortable
-
-
has_many :product_variant_groups, :as => :variantable, dependent: :destroy
-
has_many :product_variant_items, through: :product_variant_groups, dependent: :destroy
-
has_many :sub_order_items, through: :product_variant_items
-
has_many :validation_rulings, :as=>:validation_rulable
-
has_many :validation_rules, :through => :validation_rulings
-
has_and_belongs_to_many :products
-
has_many :cas_certificates, dependent: :destroy
-
has_many :cas, through: :cas_certificates
-
-
acts_as_publishable :live, :draft, :discontinue_sell
-
belongs_to :reseller_tier
-
-
serialize :icons
-
serialize :description
-
serialize :display_order
-
serialize :title
-
serialize :special_fields
-
preference :certificate_chain, :string
-
-
accepts_nested_attributes_for :product_variant_groups, allow_destroy: false
-
-
ROLES = ResellerTier.pluck(:roles).compact.push('Registered').sort
-
-
NUM_DOMAINS_TIERS = 3
-
UCC_INITIAL_DOMAINS_BLOCK = 3
-
UCC_MAX_DOMAINS = 500
-
-
FREE_CERTS_CART_LIMIT=5
-
-
DOMAINS_TEXTAREA_SEPARATOR=/[\s\n\,\+]+/
-
-
USERTRUST_EV_SUBSCRIBER_AGREEMENT="https://cdn.ssl.com/app/uploads/2015/07/ssl_certificate_subscriber_agreement.pdf"
-
USERTRUST_EV_AUTHORIZATION="https://cdn.ssl.com/app/uploads/2015/07/ev-request-form-simplified.pdf"
-
SSLCOM_EV_SUBSCRIBER_AGREEMENT="https://cdn.ssl.com/app/uploads/2017/06/SSL_com_EV_Subscriber_Agreement.pdf"
-
SSLCOM_EV_AUTHORIZATION="https://cdn.ssl.com/app/uploads/2018/03/SSL_com_EV_Request_Form_1.1.pdf"
-
SSLCOM_SUBSCRIBER_AGREEMENT="https://cdn.ssl.com/subscriber_agreement"
-
SSLCOM_CP_CPS="https://cdn.ssl.com/repository/SSLcom-CPS.pdf"
-
-
#mapping from old to v2 products (see CertificateOrder#preferred_v2_product_description)
-
MAP_TO_TRIAL=[["Comodo Trial SSL Certificate", "SSL128SCGN SSL Certificate",
-
"SSL128TRIAL30 Trial SSL Certificate",
-
"RapidSSL Trial (FreeSSL) SSL Certificate"], "high_assurance", "free"]
-
MAP_TO_OV=[["Comodo Elite SSL Certificate",
-
"Comodo Premium SSL Certificate", "Comodo InstantSSL SSL Certificate",
-
"SSL128SCG2.5 SSL Certificate", "Comodo Pro SSL Certificate",
-
"ssl certificate", "RapidSSL SSL Certificate", "XRamp Enterprise SSL Certificate"],
-
"high_assurance", "high_assurance"]
-
MAP_TO_EV=[["thawte SGC SuperCert SSL Certificate",
-
"Geotrust QuickSSL Premium SSL Certificate",
-
"Verisign Secure Site SSL Certificate", "thawte SSL Web Server Cert",
-
"XRamp Premium SSL Certificate", "SSL128SCG10 SSL Certificate",
-
"SSL123 thawte Certificate", "Comodo Platinum SSL Certificate",
-
"Verisign Secure Site Pro SSL Certificate",
-
"Comodo Gold SSL Certificate"], "ev", "ev"]
-
MAP_TO_WILDCARD=[["XRamp Premium Wildcard Certificate", "Comodo Premium Wildcard Certificate",
-
"RapidSSL Wildcard Certificate", "Comodo Platinum Wildcard Certificate",
-
"XRamp Enterprise Wildcard Certificate",
-
"SSL128WCG10 Wildcard SSL Certificate"], "wildcard", "wildcard"]
-
MAP_TO_UCC=[["SSL UC Certificate"], "ucc", "ucc"]
-
-
SUBSCRIBER_AGREEMENTS = {
-
free: {title: "Free SSL Subscriber Agreement",
-
location: "public/agreements/free_ssl_subscriber_agreement.txt"},
-
ev: {title: "EV SSL Subscriber Agreement",
-
location: "public/agreements/ssl_subscriber_agreement.txt"},
-
high_assurance: {title: "High Assurance SSL Subscriber Agreement",
-
location: "public/agreements/ssl_subscriber_agreement.txt"},
-
ucc: {title: "UCC SSL Subscriber Agreement",
-
location: "public/agreements/ssl_subscriber_agreement.txt"},
-
evucc: {title: "Enterprise EV SSL Subscriber Agreement",
-
location: "public/agreements/ssl_subscriber_agreement.txt"},
-
wildcard: {title: "Wildcard SSL Subscriber Agreement",
-
location: "public/agreements/ssl_subscriber_agreement.txt"},
-
basicssl: {title: "Basic SSL Subscriber Agreement",
-
location: "public/agreements/ssl_subscriber_agreement.txt"},
-
premiumssl: {title: "Premium SSL Subscriber Agreement",
-
location: "public/agreements/ssl_subscriber_agreement.txt"}}
-
-
WILDCARD_SWITCH_DATE = Date.strptime "02/09/2012", "%m/%d/%Y"
-
#Comodo prods:
-
#Essential Free SSL = 342
-
#Essential SSL = 301
-
#Essential SSL Wildcard = 343
-
#Positive SSL MDC = 279
-
#InstantSSL Wildcard = 35
-
#43 was the old trial cert
-
COMODO_PRODUCT_MAPPINGS =
-
{"free"=> 342, "high_assurance"=>24, "wildcard"=>35, "ev"=>337,
-
"ucc"=>361, "evucc"=>410}
-
COMODO_PRODUCT_MAPPINGS_SSL_COM =
-
{"free"=> 342,
-
Settings.subca_mapping.ov.product=>Settings.send_dv_first ? 301 : 24,
-
Settings.subca_mapping.wildcard.product=>343,
-
Settings.subca_mapping.ev.product=> Settings.send_dv_first ? 301 : 337,
-
Settings.subca_mapping.ucc.product=>279,
-
Settings.subca_mapping.evucc.product=> Settings.send_dv_first ? 279 : 410,
-
"premiumssl"=>279,
-
Settings.subca_mapping.dv.product=>301}
-
-
# ssl_ca_bundle.txt is the same as COMODOHigh-AssuranceSecureServerCA.crt
-
# file_name => description (as displayed in emails)
-
COMODO_BUNDLES = {"AddTrustExternalCARoot.crt"=>"Root CA Certificate",
-
"UTNAddTrustServerCA.crt"=>"Intermediate CA Certificate",
-
"EssentialSSLCA_2.crt"=>"Intermediate CA Certificate",
-
"UTNAddTrustSGCCA.crt"=>"Intermediate CA Certificate",
-
"ComodoUTNSGCCA.crt"=>"Intermediate CA Certificate",
-
"ssl_ca_bundle.txt"=>"High Assurance SSL.com CA Bundle",
-
"sslcom_addtrust_ca_bundle.txt"=>"SSL.com CA Bundle",
-
"sslcom_free_ca_bundle.txt"=>"Free SSL.com CA Bundle",
-
"sslcom_high_assurance_ca_bundle.txt"=>"High Assurance SSL.com CA Bundle",
-
"sslcom_ev_ca_bundle.txt"=>"EV SSL.com CA Bundle",
-
"SSLcomHighAssuranceCA.crt"=>"High Assurance SSL.com CA Bundle",
-
"free_ssl_ca_bundle.txt"=>"Free SSL.com CA Bundle",
-
"trial_ssl_ca_bundle.txt"=>"Trial SSL.com CA Bundle",
-
"ssl_ca_bundle_amazon.txt"=>"High Assurance SSL.com CA Bundle",
-
"sslcom_addtrust_ca_bundle_amazon.txt"=>"SSL.com CA Bundle",
-
"sslcom_free_ca_bundle_amazon.txt"=>"Free SSL.com CA Bundle",
-
"sslcom_high_assurance_ca_bundle_amazon.txt"=>"High Assurance SSL.com CA Bundle",
-
"sslcom_ev_ca_bundle.txt_amazon"=>"EV SSL.com CA Bundle",
-
"free_ssl_ca_bundle.txt_amazon"=>"Free SSL.com CA Bundle",
-
"trial_ssl_ca_bundle.txt_amazon"=>"Trial SSL.com CA Bundle",
-
"COMODOAddTrustServerCA.crt"=>"Intermediate CA Certificate",
-
"SSLcomPremiumEVCA.crt"=>"Intermediate CA Certificate",
-
"SSLcomAddTrustSSLCA.crt"=>"Intermediate CA Certificate",
-
"SSLcomFreeSSLCA.crt"=>"Intermediate CA Certificate",
-
"COMODOExtendedValidationSecureServerCA.crt"=>"Intermediate CA Certificate",
-
"EntrustSecureServerCA.crt"=>"Root CA Certificate",
-
"USERTrustLegacySecureServerCA.crt"=>"Intermediate CA Certificate"}
-
-
# :dir - the directory under the bundles
-
# :labels - the file names of the component ca chain certs
-
# :contents - the bundle name and component files from :labels
-
# after configuring a ca file set, run Certificate.generate_ca_certificates on the set to create the bundles
-
-
BUNDLES = {comodo: {SHA1_2012: {
-
"AddTrustExternalCARoot.crt"=>"Root CA Certificate",
-
"UTNAddTrustServerCA.crt"=>"Intermediate CA Certificate",
-
"EssentialSSLCA_2.crt"=>"Intermediate CA Certificate",
-
"UTNAddTrustSGCCA.crt"=>"Intermediate CA Certificate",
-
"ComodoUTNSGCCA.crt"=>"Intermediate CA Certificate",
-
"ssl_ca_bundle.txt"=>"High Assurance SSL.com CA Bundle",
-
"sslcom_addtrust_ca_bundle.txt"=>"SSL.com CA Bundle",
-
"sslcom_free_ca_bundle.txt"=>"Free SSL.com CA Bundle",
-
"sslcom_high_assurance_ca_bundle.txt"=>"High Assurance SSL.com CA Bundle",
-
"sslcom_ev_ca_bundle.txt"=>"EV SSL.com CA Bundle",
-
"SSLcomHighAssuranceCA.crt"=>"High Assurance SSL.com CA Bundle",
-
"free_ssl_ca_bundle.txt"=>"Free SSL.com CA Bundle",
-
"trial_ssl_ca_bundle.txt"=>"Trial SSL.com CA Bundle",
-
"ssl_ca_bundle_amazon.txt"=>"High Assurance SSL.com CA Bundle",
-
"sslcom_addtrust_ca_bundle_amazon.txt"=>"SSL.com CA Bundle",
-
"sslcom_free_ca_bundle_amazon.txt"=>"Free SSL.com CA Bundle",
-
"sslcom_high_assurance_ca_bundle_amazon.txt"=>"High Assurance SSL.com CA Bundle",
-
"sslcom_ev_ca_bundle.txt_amazon"=>"EV SSL.com CA Bundle",
-
"free_ssl_ca_bundle.txt_amazon"=>"Free SSL.com CA Bundle",
-
"trial_ssl_ca_bundle.txt_amazon"=>"Trial SSL.com CA Bundle",
-
"COMODOAddTrustServerCA.crt"=>"Intermediate CA Certificate",
-
"SSLcomPremiumEVCA.crt"=>"Intermediate CA Certificate",
-
"SSLcomAddTrustSSLCA.crt"=>"Intermediate CA Certificate",
-
"SSLcomFreeSSLCA.crt"=>"Intermediate CA Certificate",
-
"COMODOExtendedValidationSecureServerCA.crt"=>"Intermediate CA Certificate",
-
"EntrustSecureServerCA.crt"=>"Root CA Certificate",
-
"USERTrustLegacySecureServerCA.crt"=>"Intermediate CA Certificate"},
-
sha1_sslcom_2014: {
-
"AddTrustExternalCARoot.crt"=>"Root CA Certificate",
-
"UTNAddTrustServerCA.crt"=>"Intermediate CA Certificate",
-
"EssentialSSLCA_2.crt"=>"Intermediate CA Certificate",
-
"UTNAddTrustSGCCA.crt"=>"Intermediate CA Certificate",
-
"ComodoUTNSGCCA.crt"=>"Intermediate CA Certificate",
-
"ssl_ca_bundle.txt"=>"High Assurance SSL.com CA Bundle",
-
"sslcom_addtrust_ca_bundle.txt"=>"SSL.com CA Bundle",
-
"sslcom_free_ca_bundle.txt"=>"Free SSL.com CA Bundle",
-
"sslcom_high_assurance_ca_bundle.txt"=>"High Assurance SSL.com CA Bundle",
-
"sslcom_ev_ca_bundle.txt"=>"EV SSL.com CA Bundle",
-
"SSLcomHighAssuranceCA.crt"=>"High Assurance SSL.com CA Bundle",
-
"free_ssl_ca_bundle.txt"=>"Free SSL.com CA Bundle",
-
"trial_ssl_ca_bundle.txt"=>"Trial SSL.com CA Bundle",
-
"ssl_ca_bundle_amazon.txt"=>"High Assurance SSL.com CA Bundle",
-
"sslcom_addtrust_ca_bundle_amazon.txt"=>"SSL.com CA Bundle",
-
"sslcom_free_ca_bundle_amazon.txt"=>"Free SSL.com CA Bundle",
-
"sslcom_high_assurance_ca_bundle_amazon.txt"=>"High Assurance SSL.com CA Bundle",
-
"sslcom_ev_ca_bundle.txt_amazon"=>"EV SSL.com CA Bundle",
-
"free_ssl_ca_bundle.txt_amazon"=>"Free SSL.com CA Bundle",
-
"trial_ssl_ca_bundle.txt_amazon"=>"Trial SSL.com CA Bundle",
-
"COMODOAddTrustServerCA.crt"=>"Intermediate CA Certificate",
-
"SSLcomPremiumEVCA_1.crt"=>"Intermediate CA Certificate",
-
"SSLcomAddTrustSSLCA.crt"=>"Intermediate CA Certificate",
-
"SSLcomFreeSSLCA.crt"=>"Intermediate CA Certificate",
-
"COMODOExtendedValidationSecureServerCA.crt"=>"Intermediate CA Certificate",
-
"EntrustSecureServerCA.crt"=>"Root CA Certificate",
-
"USERTrustLegacySecureServerCA.crt"=>"Intermediate CA Certificate"},
-
sha2_sslcom_2014: {
-
dir: "sha2_sslcom_2014",
-
labels: {
-
"AddTrustExternalCARoot.crt"=>"Root CA Certificate",
-
"USERTrustRSAAddTrustCA.crt"=>"Intermediate CA Certificate",
-
"USERTrustRSACertificationAuthority.crt"=>"Root CA Certificate",
-
"SSLcomClientAuthenticationandEmailCA_2.crt"=>"Intermediate CA Certificate",
-
"SSLcomPremiumEVCA_2.crt"=>"Intermediate CA Certificate",
-
"SSLcomDVCA_2.crt"=>"Intermediate CA Certificate",
-
"SSLcomHighAssuranceCA_2.crt"=>"Intermediate CA Certificate",
-
"SSLcomObjectCA_2.crt"=>"Intermediate CA Certificate",
-
"ssl_ca_bundle.txt"=>"High Assurance SSL.com CA Bundle",
-
"sslcom_addtrust_ca_bundle.txt"=>"SSL.com CA Bundle",
-
"sslcom_high_assurance_ca_bundle.txt"=>"High Assurance SSL.com CA Bundle",
-
"sslcom_ev_ca_bundle.txt"=>"EV SSL.com CA Bundle",
-
"ssl_ca_bundle_amazon.txt"=>"High Assurance SSL.com CA Bundle",
-
"sslcom_addtrust_ca_bundle_amazon.txt"=>"SSL.com CA Bundle",
-
"sslcom_high_assurance_ca_bundle_amazon.txt"=>"High Assurance SSL.com CA Bundle",
-
"sslcom_ev_ca_bundle.txt_amazon"=>"EV SSL.com CA Bundle"},
-
contents: {
-
"sslcom_dv.txt" => %w(AddTrustExternalCARoot.crt USERTrustRSAAddTrustCA.crt SSLcomDVCA_2.crt),
-
"sslcom_ov.txt" => %w(AddTrustExternalCARoot.crt USERTrustRSAAddTrustCA.crt SSLcomHighAssuranceCA_2.crt),
-
"sslcom_ev.txt" => %w(AddTrustExternalCARoot.crt USERTrustRSAAddTrustCA.crt SSLcomPremiumEVCA_2.crt),
-
"sslcom_dv_amazon.txt" => %w(SSLcomDVCA_2.crt USERTrustRSAAddTrustCA.crt AddTrustExternalCARoot.crt),
-
"sslcom_ov_amazon.txt" => %w(SSLcomHighAssuranceCA_2.crt USERTrustRSAAddTrustCA.crt AddTrustExternalCARoot.crt),
-
"sslcom_ev_amazon.txt" => %w(SSLcomPremiumEVCA_2.crt USERTrustRSAAddTrustCA.crt AddTrustExternalCARoot.crt),
-
"ssl_ca_bundle.txt"=>%w(USERTrustRSAAddTrustCA.crt SSLcomHighAssuranceCA_2.crt),
-
"ssl_ca_bundle_amazon.txt"=>%w(SSLcomHighAssuranceCA_2.crt USERTrustRSAAddTrustCA.crt),
-
"sslcom_addtrust_ca_bundle.txt"=>%w(USERTrustRSAAddTrustCA.crt SSLcomDVCA_2.crt),
-
"sslcom_addtrust_ca_bundle_amazon.txt"=>%w(SSLcomDVCA_2.crt USERTrustRSAAddTrustCA.crt),
-
"sslcom_high_assurance_ca_bundle.txt"=>%w(USERTrustRSAAddTrustCA.crt SSLcomHighAssuranceCA_2.crt),
-
"sslcom_high_assurance_ca_bundle_amazon.txt"=>%w(SSLcomHighAssuranceCA_2.crt USERTrustRSAAddTrustCA.crt),
-
"sslcom_ev_ca_bundle.txt"=>%w(USERTrustRSAAddTrustCA.crt SSLcomPremiumEVCA_2.crt),
-
"sslcom_ev_ca_bundle.txt_amazon"=>%w(SSLcomPremiumEVCA_2.crt USERTrustRSAAddTrustCA.crt)}}}}
-
-
-
scope :base_products, ->{where{reseller_tier_id == nil}}
-
scope :available, ->{where{(product != 'mssl') & (serial =~ "%sslcom%") & (title << Settings.excluded_titles)}}
-
scope :sitemap, ->{where{(product != 'mssl') & (product !~ '%tr')}}
-
scope :for_sale, ->{
-
Certificate.unscoped.where(id: (Rails.cache.fetch("Certificate.for_sale") do
-
where{(product != 'mssl') & (serial =~ "%sslcom%")}.pluck(:id)
-
end))
-
}
-
-
def self.get_smime_client_products(tier=nil)
-
cur_tier = tier ? "#{tier}tr" : ""
-
Certificate.available.where(
-
"product REGEXP ?",
-
"^personal.*(basic|pro|business|enterprise|naesb-basic)#{cur_tier}$"
-
)
-
end
-
-
def self.map_to_legacy(description, mapping=nil)
-
[MAP_TO_TRIAL,MAP_TO_OV,MAP_TO_EV,MAP_TO_WILDCARD,MAP_TO_UCC].each do |m|
-
type = mapping=='renew' ? 1 : 2
-
return Certificate.find_by_product(m[type]) if m[0].include?(description)
-
end
-
end
-
-
def self.index_filter(params)
-
filters = {}
-
p = params
-
filters[:serial] = { 'LIKE' => p[:serial] } unless p[:serial].blank?
-
filters[:title] = { 'LIKE' => p[:title] } unless p[:title].blank?
-
filters[:product] = { 'LIKE' => p[:product] } unless p[:product].blank?
-
filters[:description] = { 'LIKE' => p[:description] } unless p[:description].blank?
-
unless p[:created_at_type].blank? || p[:created_at].blank?
-
operator = COMPARISON[p[:created_at_type].to_sym]
-
filters[:created_at] = { operator => DateTime.parse(p[:created_at]).beginning_of_day }
-
end
-
unless p[:updated_at_type].blank? || p[:updated_at].blank?
-
operator = COMPARISON[p[:updated_at_type].to_sym]
-
filters[:updated_at] = { operator => DateTime.parse(p[:updated_at]).end_of_day }
-
end
-
filters[:allow_wildcard_ucc] = { '=' => p[:wildcard] } unless p[:wildcard].blank?
-
filters[:reseller_tier_id] = { '=' => p[:reseller_tier_id] } unless p[:reseller_tier_id].blank?
-
result = filter(filters)
-
result
-
end
-
-
def cached_product_variant_items(options={})
-
@cpvi ||= ProductVariantItem.unscoped.where(id:
-
(Rails.cache.fetch("#{cache_key}/cached_product_variant_items/#{options.to_s}") do
-
if options[:by_serial]
-
product_variant_items.where{serial=~"%#{options[:by_serial]}%"}
-
else
-
product_variant_items
-
end.pluck(:id)
-
end))
-
end
-
memoize :cached_product_variant_items
-
-
def role_can_manage
-
Role.get_role_id Role::RA_ADMIN
-
end
-
-
def price=(amount)
-
self.amount = amount.gsub(/\./,"").to_i
-
end
-
-
def api_product_code
-
ApiCertificateRequest::PRODUCTS.find{|k,v|
-
serial =~ Regexp.new('^'+v)
-
}[0].to_s
-
end
-
-
def items_by_duration
-
ProductVariantItem.where(id: (Rails.cache.fetch("#{cache_key}/items_by_duration") do
-
product_variant_groups.includes(:product_variant_items).duration.map(&:product_variant_items).
-
flatten.sort{|a,b|a.value.to_i <=> b.value.to_i}.map(&:id)
-
end))
-
end
-
memoize :items_by_duration
-
-
def pricing(certificate_order,certificate_content)
-
ratio = certificate_order.signed_certificates.try(:last) ? certificate_order.duration_remaining : 1
-
durations=[]
-
result={}
-
num_durations.times do |i|
-
durations <<
-
if is_ucc?
-
tiers=[]
-
num_domain_tiers.times do |j|
-
tiers << ((items_by_domains(true)[i][j].price*((j==0)?3:1))*ratio).format
-
-
end
-
tiers
-
else
-
(items_by_duration[i].price*ratio).format
-
end
-
end
-
result.merge!(durations: durations)
-
if is_ucc? || is_wildcard?
-
licenses=[]
-
num_durations.times do |i|
-
licenses << (items_by_server_licenses[i].price*ratio).format
-
end
-
result.merge!(licenses: licenses, domains: certificate_content.domains)
-
end
-
result.merge!(product: product)
-
end
-
-
# use multi_dim to return a multi dimension array of domain types
-
def items_by_domains(multi_dim=false)
-
if is_ucc?
-
unless multi_dim
-
product_variant_groups.domains.includes(:product_variant_items).map(&:product_variant_items).flatten
-
else
-
unless is_ev?
-
product_variant_items.where{serial=~"%yrdm%"}.flatten.zip(
-
product_variant_items.where{serial=~"%yradm%"}.flatten,
-
product_variant_items.where{serial=~"%yrwcdm%"}.flatten)
-
else
-
product_variant_items.where{serial=~"%yrdm%"}.flatten.zip(
-
product_variant_items.where{serial=~"%yradm%"}.flatten)
-
end
-
end
-
end
-
end
-
memoize :items_by_domains
-
-
def items_by_server_licenses
-
product_variant_groups.server_licenses.includes(:product_variant_items).map(&:product_variant_items).flatten if
-
(is_ucc? || is_wildcard?)
-
end
-
memoize :items_by_server_licenses
-
-
def first_domains_tiers
-
if is_ucc?
-
items_by_domains(true).transpose[0]
-
end
-
end
-
-
def num_durations
-
if is_ucc?
-
items_by_domains.size / num_domain_tiers
-
else
-
items_by_duration.size
-
end
-
end
-
-
def num_domain_tiers
-
if is_ucc?
-
if is_ev? or is_premium_ssl?
-
NUM_DOMAINS_TIERS.to_i - 1
-
else
-
NUM_DOMAINS_TIERS.to_i
-
end
-
end
-
end
-
-
def first_duration
-
@fcpvi ||= cached_product_variant_items.first
-
end
-
-
def last_duration
-
@lcpvi ||= cached_product_variant_items.last
-
end
-
-
# is is true for SAN and EV SAN certs
-
def is_ucc?
-
product.include?('ucc') || product.include?('premiumssl')
-
end
-
-
# true for EV SAN only
-
def is_evucc?
-
product =~ /\Aevucc/
-
end
-
-
def admin_submit_csr?
-
is_evcs? or
-
is_cs? or
-
is_smime_or_client?
-
end
-
-
def is_wildcard?
-
product =~ /wildcard/
-
end
-
-
def is_basic?
-
product =~ /basic/
-
end
-
-
def is_high_assurance?
-
product =~ /high_assurance/
-
end
-
-
def is_browser_generated_capable?
-
is_code_signing? || is_client?
-
end
-
-
def is_personal?
-
product.include?('personal')
-
end
-
-
def is_document_signing?
-
product.include?('document_signing')
-
end
-
-
def is_premium_ssl?
-
product =~ /\Apremiumssl/
-
end
-
-
alias_method "is_dv_or_basic?".to_sym, "is_dv?".to_sym
-
-
def is_free?
-
product =~ /\Afree/
-
end
-
-
def is_multi?
-
is_ucc? || is_wildcard?
-
end
-
-
# use the essential ssl chain certs for these products
-
# Essential Free SSL = 342
-
# Essential SSL = 301
-
# Essential SSL Wildcard = 343
-
# Positive SSL MDC = 279
-
def is_essential_ssl?
-
[342,301,343,279].include? comodo_product_id
-
end
-
-
def find_tier(tier)
-
Certificate.available.find_by_product(product_root+tier+'tr')
-
end
-
-
def is_single?
-
!is_multi?
-
end
-
-
def allow_wildcard_ucc?
-
(is_ev? or is_premium_ssl?) ? false : true
-
#true
-
#allow_wildcard_ucc
-
end
-
-
def site_seal
-
SiteSeal.new(SiteSeal.generate_options(product))
-
end
-
-
def tiered?
-
!reseller_tier.blank?
-
end
-
-
def product_root
-
get_root(self.product)
-
end
-
-
def serial_root
-
get_root(self.serial)
-
end
-
-
def untiered
-
if reseller_tier.blank?
-
self
-
else
-
Certificate.available.find_by_product product_root
-
end
-
end
-
-
def self.root_products
-
Certificate.base_products.available.sort{|a,b|
-
a.display_order['all'] <=> b.display_order['all']}
-
end
-
-
def self.tiered_products(tier)
-
Certificate.available.sort{|a,b|
-
a.display_order['all'] <=> b.display_order['all']}.find_all{|c|
-
c.product=~Regexp.new(tier)}
-
end
-
-
def to_param
-
product_root
-
end
-
-
def has_locked_registrant?
-
is_code_signing? || is_ev? || is_ov?
-
end
-
-
def subscriber_agreement
-
SUBSCRIBER_AGREEMENTS[product_root.to_sym]
-
end
-
-
def subscriber_agreement_content
-
File.read(subscriber_agreement[:location])
-
end
-
-
def duration_in_days(duration)
-
if is_ucc?
-
index = duration.to_i
-
items_by_domains.select{|n|n.display_order==index}.last.value
-
else
-
items_by_duration[duration.to_i-1].value
-
end
-
end
-
-
def duration_index(value)
-
if is_ucc?
-
items_by_domains.find{|d|d.value==value.to_s}.display_order
-
else
-
items_by_duration.map(&:value).index(value.to_s)+1
-
end
-
end
-
-
def certificate_chain_names
-
parse_certificate_chain.transpose[0]
-
end
-
-
def certificate_chain_types
-
parse_certificate_chain.transpose[1]
-
end
-
-
def parse_certificate_chain
-
preferred_certificate_chain.split(",").
-
map(&:strip).map{|a|a.split(":")}
-
end
-
-
def comodo_product_id
-
if self.serial=~/256sslcom/
-
COMODO_PRODUCT_MAPPINGS_SSL_COM[product_root]
-
else
-
COMODO_PRODUCT_MAPPINGS[product_root]
-
end
-
end
-
-
def skip_verification?
-
false
-
end
-
-
def self.xcert_certum(x509_certificate,tagged_xcert=false)
-
case x509_certificate.serial.to_s
-
when "8875640296558310041"
-
tagged_xcert ? SignedCertificate.enclose_with_tags(CERTUM_XSIGN) : CERTUM_XSIGN
-
when "6248227494352943350","5688664355526928916"
-
tagged_xcert ? SignedCertificate.enclose_with_tags(CERTUM_XSIGN_EV) : CERTUM_XSIGN_EV
-
when "8495723813297216424"
-
tagged_xcert ? SignedCertificate.enclose_with_tags(RSA_TO_ECC_XSIGN) : RSA_TO_ECC_XSIGN
-
when "3182246526754555285"
-
tagged_xcert ? SignedCertificate.enclose_with_tags(RSA_TO_ECC_EV_XSIGN) : RSA_TO_ECC_EV_XSIGN
-
else
-
x509_certificate.to_s
-
end
-
end
-
-
# options = {bundles: Certificate::BUNDLES[:comodo][:sha2_sslcom_2014]}
-
def self.generate_ca_certificates(options)
-
dir=Settings.intermediate_certs_path+options[:bundles][:dir]+"/"
-
options[:bundles][:contents].each do |k,v|
-
certfile="#{dir}#{k}"
-
File.open(certfile, 'wb') do |f|
-
tmp=""
-
v.each do |file_name|
-
file=File.new("#{dir}"+file_name.strip, "r")
-
tmp << file.readlines.join("")
-
end
-
f.write tmp
-
end
-
end
-
end
-
-
def order_description
-
try(:description_with_tier) ? certificate_type(self) : description_with_tier
-
end
-
-
# this method duplicates, modifies or adds reseller tiers to a certificate
-
# deep level copying function, copies own attributes and then duplicates the sub groups and items
-
# options[:new_serial] - new serial number, the numbered reseller tier will be preserved
-
# options[:old_pvi_serial] - old product_variant_item serial number
-
# options[:new_pvi_serial] - new product_variant_item serial number
-
# options[:reseller_tier_label] - label of the reseller tier to create or update
-
# options[:discount_rate] - reduce price by this much
-
def duplicate(options)
-
now=DateTime.now
-
new_cert = self.dup
-
new_cert.product="#{self.product}"
-
if options[:new_serial] # changing serial
-
m=self.serial.match(/.*?((\d+|\-.+?)tr)\z/)
-
new_cert.serial=options[:new_serial]+(m.blank? ? "" : m[1])
-
elsif options[:reseller_tier_label]
-
new_cert.product<<"-#{options[:reseller_tier_label]}tr"
-
if Certificate.find_by_serial("#{self.serial}-#{options[:reseller_tier_label]}tr") # adding reseller tier
-
new_cert = Certificate.find_by_serial("#{self.serial}-#{options[:reseller_tier_label]}tr") # update
-
else
-
new_cert.serial="#{self.serial}-#{options[:reseller_tier_label]}tr" # create reseller tier
-
end
-
end
-
new_cert.save
-
self.product_variant_groups.each do |pvg|
-
new_pvg = pvg.dup
-
new_cert.product_variant_groups << new_pvg
-
pvg.product_variant_items.each_with_index do |pvi, i|
-
if options[:product].blank? or i < options[:product][:price_adjusts].first[1].count
-
new_pvi=pvi.dup
-
if options[:old_pvi_serial] and options[:new_pvi_serial]
-
new_pvi.serial=pvi.serial.gsub(options[:old_pvi_serial], options[:new_pvi_serial])
-
elsif options[:reseller_tier_label]
-
if ProductVariantItem.find_by_serial("#{pvi.serial}-#{options[:reseller_tier_label]}tr") # adding reseller tier
-
new_pvi = ProductVariantItem.find_by_serial("#{pvi.serial}-#{options[:reseller_tier_label]}tr") # update
-
else
-
new_pvi.serial="#{pvi.serial}-#{options[:reseller_tier_label]}tr" # create reseller tier
-
end
-
end
-
new_pvi.amount=((new_pvi.amount || 0)*options[:discount_rate]).ceil if options[:discount_rate]
-
new_pvg.product_variant_items << new_pvi
-
unless pvi.sub_order_item.blank?
-
if new_pvi.sub_order_item.blank?
-
new_pvi.sub_order_item=pvi.sub_order_item.dup
-
end
-
new_pvi.sub_order_item.amount=((new_pvi.sub_order_item.amount || 0)*options[:discount_rate]).ceil if options[:discount_rate]
-
new_pvi.sub_order_item.save
-
end
-
end
-
end
-
end
-
new_cert
-
end
-
-
def get_root(extract_from)
-
if extract_from =~ /-?\dtr\z/
-
extract_from.gsub(/-?\dtr\z/,"")
-
elsif extract_from =~ /.+(-.+?tr)\z/
-
extract_from.sub $1, ""
-
else
-
extract_from
-
end
-
end
-
-
# this method duplicates the base certificate product along with all reseller_tiers
-
def duplicate_w_tiers(options)
-
sr = "#{self.serial_root}%"
-
Certificate.where{serial =~ sr}.map {|c| c.duplicate(options)}
-
end
-
-
# this method duplicates the base certificate product along with all standard 5 reseller_tiers
-
def duplicate_standard_tiers(options)
-
standard = "#{self.serial_root}%"
-
custom = "#{self.serial_root}-%"
-
Certificate.where{serial =~ standard}.where{serial !~ custom}.map {|c|
-
c.duplicate(options)}
-
end
-
-
def self.list_default_cas
-
all.map do |cert|
-
[cert.product,cert.cas.default.map(&:id)] unless cert.cas.default.map(&:id).empty?
-
end.compact
-
end
-
-
def max_duration
-
if is_smime_or_client?
-
CertificateOrder::CLIENT_MAX_DURATION
-
elsif is_code_signing?
-
CertificateOrder::CS_MAX_DURATION
-
elsif is_ev?
-
CertificateOrder::EV_SSL_MAX_DURATION
-
elsif is_time_stamping?
-
CertificateOrder::TS_MAX_DURATION
-
else # assume non EV SSL
-
CertificateOrder::SSL_MAX_DURATION
-
end
-
end
-
-
# use this function to update prices via ResellerTier#update_prices
-
def prices_matrix(indexed=true)
-
if indexed
-
prices={}
-
product_variant_items.includes{product_variant_group}.map do |pvi|
-
prices.merge!(pvi.id=>[pvi.product_variant_group.variantable(Certificate).title,
-
pvi.product_variant_group.title, pvi.title, pvi.amount])
-
end
-
else
-
prices=[]
-
product_variant_items.includes{product_variant_group}.map do |pvi|
-
prices<<{variantable_title: pvi.product_variant_group.variantable(Certificate).title,
-
pvg_title: pvi.product_variant_group.title, pvi_title: pvi.title, pvi_amount: pvi.amount}
-
end
-
end
-
prices
-
end
-
-
private
-
-
# renames 'product' field for certificate including the reseller tiers
-
def self.rename(oldname, newname)
-
certificates = Certificate.unscoped.where{product =~ "%#{oldname}%"}
-
certificates.each {|certificate| certificate.update_column :product, certificate.product.gsub(oldname, newname)}
-
end
-
-
# one-time call to create ssl.com product lines to supplant Comodo Essential SSL
-
def self.create_sslcom_products
-
%w(evucc ucc ev ov dv wc).each do |serial|
-
s = self.serial+"%"
-
Certificate.where{serial =~ s}.first.duplicate_standard_tiers serial+"256sslcom"
-
end
-
end
-
-
# one-time call to create ssl.com premium products
-
def self.create_premium_ssl
-
c=Certificate.available.find_by_product "ucc"
-
certs = c.duplicate_standard_tiers new_serial: "premium256sslcom", old_pvi_serial: "ucc256ssl",
-
new_pvi_serial: "premium256ssl"
-
title = "Premium Multi-subdomain SSL"
-
description={
-
"certificate_type" => "Premium SSL",
-
"points" => "<div class='check'>quick domain validation</div>
-
<div class='check'>results in higher sales conversion</div>
-
<div class='check'>$10,000 USD insurance guarantee</div>
-
<div class='check'>works on MS Exchange or OWA</div>
-
<div class='check'>activates SSL Secure Site Seal</div>
-
<div class='check'>2048 bit public key encryption</div>
-
<em style='color:#333;display:block;padding:5px 20px;'>also comes with the following</em>
-
<div class='check'>quick issuance</div>
-
<div class='check'>30 day money-back guarantee</div>
-
<div class='check'>24 hour support</div>
-
<div class='check'>unlimited reissuances</div>",
-
"validation_level" => "domain",
-
"summary" => "for securing small to medium sites",
-
"abbr" => "Premium SSL"
-
}
-
certs.each do |c|
-
c.update_attributes title: title,
-
description: description,
-
product: c.product.gsub(/\Aucc/, "premiumssl")
-
end
-
price_adjusts={sslcompremium256ssl1yrdm: [9900, 17820, 25245, 31680, 37125],
-
sslcompremium256ssl1yrdm1tr: [9900, 17820, 25245, 31680, 37125],
-
sslcompremium256ssl1yrdm2tr: [7920, 14256, 20196, 25344, 29700],
-
sslcompremium256ssl1yrdm3tr: [7425, 13365, 18934, 23760, 27844],
-
sslcompremium256ssl1yrdm4tr: [6831, 12296, 17419, 21859, 25616],
-
sslcompremium256ssl1yrdm5tr: [5940, 10692, 15147, 19008, 22275]
-
}
-
price_adjusts.each do |k,v|
-
serials=[]
-
1.upto(5){|i|serials<<k.to_s.gsub(/1yr/, i.to_s+"yr")}
-
serials.each_with_index {|s, i|ProductVariantItem.find_by_serial(s).update_attribute(:amount, (v[i]/3).ceil)}
-
end
-
end
-
-
# sslcomevucc256ssl1yrdm - initial 3 domains
-
# sslcomevucc256ssl1yradm - additional domains
-
# each column is an incremented a year and represents cost of 3 domains
-
#
-
# use root like sslcomevucc256ssl1yr
-
def self.change_domain_pricing(pvi)
-
years = 2 # 5 for standard
-
# ev ssl
-
price_adjusts={"#{pvi}dm".to_sym => [13300, 21280], # initial 3 domains
-
"#{pvi}dm1tr".to_sym => [13300, 21280],
-
"#{pvi}dm2tr".to_sym => [10640, 17024],
-
"#{pvi}dm3tr".to_sym => [9975, 15960],
-
"#{pvi}dm4tr".to_sym => [9310, 14896],
-
"#{pvi}dm5tr".to_sym => [7980, 12768],
-
"#{pvi}adm".to_sym => [12900, 20640], # domains after 3rd
-
"#{pvi}adm1tr".to_sym => [12900, 20640],
-
"#{pvi}adm2tr".to_sym => [10320, 16512],
-
"#{pvi}adm3tr".to_sym => [9675, 15480],
-
"#{pvi}adm4tr".to_sym => [9030, 14448],
-
"#{pvi}adm5tr".to_sym => [7740, 12384]
-
}
-
# standard ssl
-
# price_adjusts={"#{pvi}".to_sym => [9900, 17820, 25245, 31680, 37125],
-
# "#{pvi}1tr".to_sym => [9900, 17820, 25245, 31680, 37125],
-
# "#{pvi}2tr".to_sym => [7920, 14256, 20196, 25344, 29700],
-
# "#{pvi}3tr".to_sym => [7425, 13365, 18934, 23760, 27844],
-
# "#{pvi}4tr".to_sym => [6831, 12296, 17419, 21859, 25616],
-
# "#{pvi}5tr".to_sym => [5940, 10692, 15147, 19008, 22275]
-
# }
-
price_adjusts.each do |k,v|
-
serials=[]
-
1.upto(years){|i|serials<<k.to_s.gsub(/1yr/, i.to_s+"yr")}
-
serials.each_with_index {|s, i|ProductVariantItem.find_by_serial(s).update_attribute(:amount, (v[i]).ceil)}
-
end
-
end
-
-
def self.create_basic_ssl
-
c=Certificate.available.find_by_product "high_assurance"
-
certs = c.duplicate_standard_tiers new_serial: "basic256sslcom", old_pvi_serial: "ov256ssl", new_pvi_serial: "basic256ssl"
-
title = "Basic SSL"
-
description={
-
"certificate_type" => "Basic SSL",
-
"points" => "<div class='check'>quick domain validation</div>
-
<div class='check'>results in higher sales conversion</div>
-
<div class='check'>$10,000 USD insurance guarantee</div>
-
<div class='check'>activates SSL Secure Site Seal</div>
-
<div class='check'>2048 bit public key encryption</div>
-
<em style='color:#333;display:block;padding:5px 20px;'>also comes with the following</em>
-
<div class='check'>quick issuance</div>
-
<div class='check'>30 day money-back guarantee</div>
-
<div class='check'>24 hour support</div>
-
<div class='check'>unlimited reissuances</div>",
-
"validation_level" => "domain",
-
"summary" => "for securing small sites",
-
"abbr" => "Basic SSL"
-
}
-
certs.each do |c|
-
c.update_attributes title: title,
-
description: description,
-
product: c.product.gsub(/\Ahigh_assurance/, "basicssl"),
-
icons: c.icons.merge!("main"=> "silver_lock_lg.gif")
-
end
-
price_adjusts={sslcombasic256ssl1yr: [4900, 8820, 12495, 15680, 18375],
-
sslcombasic256ssl1yr1tr: [4900, 8820, 12495, 15680, 18375],
-
sslcombasic256ssl1yr2tr: [3920, 7056, 9996, 12544, 14700],
-
sslcombasic256ssl1yr3tr: [3675, 6615, 9371, 11760, 13781],
-
sslcombasic256ssl1yr4tr: [3381, 6086, 8622, 10819, 12679],
-
sslcombasic256ssl1yr5tr: [2940, 5292, 7497, 9408, 11025]
-
}
-
price_adjusts.each do |k,v|
-
serials=[]
-
1.upto(5){|i|serials<<k.to_s.gsub(/1yr/, i.to_s+"yr")}
-
serials.each_with_index {|s, i|ProductVariantItem.find_by_serial(s).update_attribute(:amount, v[i])}
-
end
-
end
-
-
def self.create_code_signing
-
c=Certificate.available.find_by_product "high_assurance"
-
certs = c.duplicate_standard_tiers new_serial: "codesigning256sslcom", old_pvi_serial: "ov256ssl",
-
new_pvi_serial: "codesigning256ssl"
-
title = "Code Signing"
-
description={
-
"certificate_type" => title,
-
"points" => "<div class='check'>organization validation</div>
-
<div class='check'>results in higher sales conversion</div>
-
<div class='check'>$150,000 USD insurance guarantee</div>
-
<div class='check'>activates SSL Secure Site Seal</div>
-
<div class='check'>2048 bit public key encryption</div>
-
<em style='color:#333;display:block;padding:5px 20px;'>also comes with the following</em>
-
<div class='check'>quick issuance</div>
-
<div class='check'>30 day money-back guarantee</div>
-
<div class='check'>24 hour support</div>
-
<div class='check'>unlimited reissuances</div>",
-
"validation_level" => "organization",
-
"summary" => "for securing installable apps and plugins",
-
"abbr" => title
-
}
-
certs.each do |c|
-
c.update_attributes title: title,
-
description: description,
-
product: c.product.gsub(/\Ahigh_assurance/, "code_signing"),
-
icons: c.icons.merge!("main"=> "gold_lock_lg.gif")
-
end
-
price_adjusts={sslcomcodesigning256ssl1yr: [12900, 23220, 32895, 41280, 48375, 54180, 58695, 61920, 63855, 64500],
-
sslcomcodesigning256ssl1yr1tr: [12900, 23220, 32895, 41280, 48375, 54180, 58695, 61920, 63855, 64500],
-
sslcomcodesigning256ssl1yr2tr: [10320, 18576, 26316, 33024, 38700, 43344, 46956, 49536, 51084, 51600],
-
sslcomcodesigning256ssl1yr3tr: [9675, 17415, 24671, 30960, 36281, 40635, 44021, 46440, 47891, 48375],
-
sslcomcodesigning256ssl1yr4tr: [9030, 16254, 23026, 28896, 33862, 37926, 41086, 43344, 44698, 45150],
-
sslcomcodesigning256ssl1yr5tr: [7740, 13932, 19737, 24768, 29025, 32508, 35217, 37152, 38313, 38700]
-
}
-
price_adjusts.each do |k,v|
-
serials=[]
-
1.upto(10){|i|serials<<k.to_s.gsub(/1yr/, i.to_s+"yr")}
-
serials.each_with_index {|s, i|
-
if ProductVariantItem.find_by_serial(s)
-
ProductVariantItem.find_by_serial(s).update_attribute(:amount, v[i])
-
else
-
if s.last(3)=~/\d+tr/ #assume a reseller tier
-
pvg = certs.find{|c|c.serial.last(3)==s.last(3)}.product_variant_groups.last
-
else #assume non reseller
-
pvg = certs.first.product_variant_groups.last
-
end
-
pvi = pvg.product_variant_items.last
-
years = i+1
-
pvg.product_variant_items.create(serial: s, amount: v[i], title: pvi.title.gsub(/\d/,years.to_s),
-
status: pvi.status, description: pvi.description.gsub(/\d/,years.to_s),
-
text_only_description: pvi.text_only_description.gsub(/\d/,years.to_s), display_order: years.to_s,
-
item_type: pvi.item_type, value: 365*years, published_as: pvi.published_as)
-
end
-
}
-
end
-
end
-
-
def self.create_ev_code_signing
-
c=Certificate.available.find_by_product "high_assurance"
-
certs = c.duplicate_standard_tiers new_serial: "evcodesigning256sslcom", old_pvi_serial: "ov256ssl",
-
new_pvi_serial: "evcodesigning256ssl"
-
title = "EV Code Signing"
-
description={
-
"certificate_type" => title,
-
"points" => "<div class='check'>extended validation</div>
-
<div class='check'>results in higher sales conversion</div>
-
<div class='check'>$2 million USD insurance guarantee</div>
-
<div class='check'>works with Microsoft Smartscreen</div>
-
<div class='check'>2048 bit public key encryption</div>
-
<em style='color:#333;display:block;padding:5px 20px;'>also comes with the following</em>
-
<div class='check'>quick issuance</div>
-
<div class='check'>30 day money-back guarantee</div>
-
<div class='check'>stored on fips 140-2 USB token</div>
-
<div class='check'>24 hour support</div>",
-
"validation_level" => "extended",
-
"summary" => "for securing installable apps and plugins",
-
"abbr" => title
-
}
-
certs.each do |c|
-
c.update_attributes title: title,
-
description: description,
-
product: c.product.gsub(/\Ahigh_assurance/, "ev-code-signing"),
-
icons: c.icons.merge!("main"=> "gold_lock_lg.gif")
-
end
-
price_adjusts={sslcomevcodesigning256ssl1yr: [34900, 59800, 74700],
-
sslcomevcodesigning256ssl1yr1tr: [34900, 59800, 74700],
-
sslcomevcodesigning256ssl1yr2tr: [27920, 47840, 59760],
-
sslcomevcodesigning256ssl1yr3tr: [26175, 44850, 56025],
-
sslcomevcodesigning256ssl1yr4tr: [24430, 41860, 52290],
-
sslcomevcodesigning256ssl1yr5tr: [20940, 35880, 44820]
-
}
-
price_adjusts.each do |k,v|
-
serials=[]
-
1.upto(3){|i|serials<<k.to_s.gsub(/1yr/, i.to_s+"yr")}
-
serials.each_with_index {|s, i|
-
if ProductVariantItem.find_by_serial(s)
-
ProductVariantItem.find_by_serial(s).update_attribute(:amount, v[i])
-
else
-
if s.last(3)=~/\d+tr/ #assume a reseller tier
-
pvg = certs.find{|c|c.serial.last(3)==s.last(3)}.product_variant_groups.last
-
else #assume non reseller
-
pvg = certs.first.product_variant_groups.last
-
end
-
pvi = pvg.product_variant_items.last
-
years = i+1
-
pvg.product_variant_items.create(serial: s, amount: v[i], title: pvi.title.gsub(/\d/,years.to_s),
-
status: pvi.status, description: pvi.description.gsub(/\d/,years.to_s),
-
text_only_description: pvi.text_only_description.gsub(/\d/,years.to_s), display_order: years.to_s,
-
item_type: pvi.item_type, value: 365*years, published_as: pvi.published_as)
-
end
-
}
-
end
-
# delete 4 and 5 year durations carried over from high assurance
-
ProductVariantItem.where{(serial=~"%evcodesigning256ssl5yr%") | (serial=~"%evcodesigning256ssl4yr%")}.delete_all
-
end
-
-
def self.create_email_certs
-
Certificate.purge %w(personalbasic personalbusiness personalpro personalenterprise naesbbasic)
-
products=[{serial_root: "personalbasic",title: "Personal Basic",validation_type: "class 1",
-
summary: "for authenticating and encrypting email and well as client services",
-
product: "personal-basic",
-
price_adjusts:{sslcompersonalbasic256ssl1yr: [3000, 4500, 6000],
-
sslcompersonalbasic256ssl1yr1tr: [3000, 4500, 6000],
-
sslcompersonalbasic256ssl1yr2tr: [3000, 4500, 6000],
-
sslcompersonalbasic256ssl1yr3tr: [3000, 4500, 6000],
-
sslcompersonalbasic256ssl1yr4tr: [3000, 4500, 6000],
-
sslcompersonalbasic256ssl1yr5tr: [3000, 4500, 6000]
-
}},
-
{serial_root: "personalbusiness",title: "Personal Business",validation_type: "class 2",
-
summary: "for authenticating and encrypting email and well as client services",
-
product: "personal-business",
-
price_adjusts:{sslcompersonalbusiness256ssl1yr: [9000, 12000, 15000],
-
sslcompersonalbusiness256ssl1yr1tr: [9000, 12000, 15000],
-
sslcompersonalbusiness256ssl1yr2tr: [9000, 12000, 15000],
-
sslcompersonalbusiness256ssl1yr3tr: [9000, 12000, 15000],
-
sslcompersonalbusiness256ssl1yr4tr: [9000, 12000, 15000],
-
sslcompersonalbusiness256ssl1yr5tr: [9000, 12000, 15000]
-
}},
-
{serial_root: "personalpro",title: "Personal Pro",validation_type: "class 2",
-
summary: "for authenticating and encrypting email and well as client services",
-
product: "personal-pro",
-
price_adjusts:{sslcompersonalpro256ssl1yr: [7000, 8000, 9000],
-
sslcompersonalpro256ssl1yr1tr: [7000, 8000, 9000],
-
sslcompersonalpro256ssl1yr2tr: [7000, 8000, 9000],
-
sslcompersonalpro256ssl1yr3tr: [7000, 8000, 9000],
-
sslcompersonalpro256ssl1yr4tr: [7000, 8000, 9000],
-
sslcompersonalpro256ssl1yr5tr: [7000, 8000, 9000]
-
}},
-
{serial_root: "personalenterprise",title: "Personal Enterprise",validation_type: "class 2",
-
summary: "for authenticating and encrypting email and well as client services",
-
product: "personal-enterprise",
-
price_adjusts:{sslcompersonalenterprise256ssl1yr: [24900, 49900, 59900],
-
sslcompersonalenterprise256ssl1yr1tr: [24900, 49900, 59900],
-
sslcompersonalenterprise256ssl1yr2tr: [24900, 49900, 59900],
-
sslcompersonalenterprise256ssl1yr3tr: [24900, 49900, 59900],
-
sslcompersonalenterprise256ssl1yr4tr: [24900, 49900, 59900],
-
sslcompersonalenterprise256ssl1yr5tr: [24900, 49900, 59900]
-
}},
-
{serial_root: "documentsigning",title: "Document Signing",validation_type: "basic",
-
summary: "for signing and authenticating documents such as Adobe pdf, Microsoft Office, OpenOffice and LibreOffice",
-
product: "document-signing",
-
points: "<div class='check'>Legally binding and complies with the U.S. Federal ESIGN Act</div>
-
<div class='check'>Stored on USB etoken for 2 factor authentication</div>
-
<div class='check'>No required plugins or software</div>
-
<div class='check'>Customizable appearance of digital signature</div>
-
<div class='check'>Shows signed by a person OR department</div>
-
<div class='check'>30 day money-back guarantee </div>
-
<div class='check'>24 hour 5-star support</div>",
-
price_adjusts:{sslcomdocumentsigning1yr: [34900,64900,84900],
-
sslcomdocumentsigning1yr1tr: [34900,64900,84900],
-
sslcomdocumentsigning1yr2tr: [12000,15000],
-
sslcomdocumentsigning1yr3tr: [11250,15000],
-
sslcomdocumentsigning1yr4tr: [10500,15000],
-
sslcomdocumentsigning1yr5tr: [9000,15000],
-
sslcomdocumentsigning1yr6tr: [7500,15000],
-
sslcomdocumentsigning1yr7tr: [6000,15000]
-
}},
-
{serial_root: "naesbbasic",title: "NAESB Basic",validation_type: "basic",
-
summary: "for authenticating and encrypting email and well as client services",
-
special_fields: %w(entity_code),
-
product: "personal-naesb-basic",
-
points: "<div class='check'>Required for NAESB EIR, OASIS and e-Tagging applications</div>
-
<div class='check'>Used for Energy Industry website client authentications</div>
-
<div class='check'>Issued from NAESB ACA SSL.com</div>
-
<div class='check'>2048 bit public key encryption</div>
-
<div class='check'>RSA and ECC supported</div>
-
<div class='check'>Quick issuance</div>
-
<div class='check'>30 day money-back guarantee </div>
-
<div class='check'>24 hour 5-star support</div>",
-
price_adjusts:{sslcomnaesbbasicclient1yr: [7500,15000],
-
sslcomnaesbbasicclient1yr1tr: [7500,15000],
-
sslcomnaesbbasicclient1yr2tr: [6000,12000],
-
sslcomnaesbbasicclient1yr3tr: [5625,11250],
-
sslcomnaesbbasicclient1yr4tr: [5025,10500],
-
sslcomnaesbbasicclient1yr5tr: [4500,9000],
-
sslcomnaesbbasicclient1yr6tr: [3750,7500],
-
sslcomnaesbbasicclient1yr7tr: [2625,5250]
-
}}]
-
products.each do |p|
-
c=Certificate.available.find_by_product "high_assurance"
-
certs = c.duplicate_w_tiers(product: p, new_serial: "#{p[:serial_root]}256sslcom",
-
old_pvi_serial: "ov256ssl", new_pvi_serial: "#{p[:serial_root]}256ssl")
-
title = p[:title]
-
description={
-
"certificate_type" => title,
-
"points" => p[:points] || "",
-
"validation_level" => p[:validation_type],
-
"summary" => p[:summary],
-
"abbr" => title
-
}
-
certs.each do |c|
-
c.update_attributes title: title,
-
description: description,
-
special_fields: p[:special_fields],
-
product: c.product.gsub(/\Ahigh_assurance/, p[:product]),
-
icons: c.icons.merge!("main"=> "gold_lock_lg.gif")
-
end
-
certs.each{ |c| c.product_variant_items.where{display_order > 3}.destroy_all}
-
p[:price_adjusts].each do |k,v|
-
serials=[]
-
num_years=v.count
-
1.upto(num_years){|i|serials<<k.to_s.gsub(/1yr/, i.to_s+"yr")}
-
serials.each_with_index {|s, i|
-
if ProductVariantItem.find_by_serial(s)
-
ProductVariantItem.find_by_serial(s).update_attribute(:amount, v[i])
-
else
-
if s.last(3)=~/\d+tr/ #assume a reseller tier
-
pvg = certs.find{|c|c.serial.last(3)==s.last(3)}.product_variant_groups.last
-
else #assume non reseller
-
pvg = certs.first.product_variant_groups.last
-
end
-
pvi = pvg.product_variant_items.last
-
years = i+1
-
pvg.product_variant_items.create(serial: s, amount: v[i], title: pvi.title.gsub(/\d/,years.to_s),
-
status: pvi.status, description: pvi.description.gsub(/\d/,years.to_s),
-
text_only_description: pvi.text_only_description.gsub(/\d/,years.to_s),
-
display_order: years.to_s,
-
item_type: pvi.item_type, value: 365*years, published_as: pvi.published_as)
-
pvg.product_variant_items.where{serial << serials}.delete_all
-
end
-
}
-
end
-
end
-
end
-
-
def self.purge(serial_snippets=[])
-
serial_snippets.each do |serial_snippet|
-
Certificate.where{serial=~"%#{serial_snippet}%"}.each do |c|
-
c.product_variant_groups.each do |pvg|
-
pvg.product_variant_items.each do |pvi|
-
pvi.destroy
-
end
-
pvg.destroy
-
end
-
c.destroy
-
end
-
end
-
end
-
-
def self.transform_products_05282012
-
create_premium_ssl
-
create_basic_ssl
-
Certificate.where{product =~ "ev%"}.each do |c|
-
c.description.merge!(certificate_type: "Enterprise EV")
-
c.title = "Enterprise EV SSL"
-
c.save
-
end
-
Certificate.where{product =~ "evucc%"}.each do |c|
-
c.description.merge!(certificate_type: "Enterprise EV UCC")
-
c.title = "Enterprise EV Multi-domain UCC SSL"
-
c.save
-
end
-
end
-
-
def self.reduce_years(title="assureguard-dv%", days=1095)
-
self.where{product =~ title}.each do |c|
-
c.cached_product_variant_items.where{value > days}.each{|pvi|pvi.delete}
-
end
-
end
-
-
# title - a specific tier of products
-
# prices - an ordered array of prices in cents USD. For ucc, use a 2 dimensional array with the structure
-
# [[1-3 domain price, 4+ domain price, wildcard price]] in increasing order of years
-
#
-
# ie Certificate.change_prices "assureguard-ucc", [[18500,18500,49500],[31400,31500,82500],[43466,43500,116500]]
-
# Certificate.change_prices("assureguard-evucc", [[37500,37500],[58500,58500]])
-
-
def self.change_prices(title="assureguard-dv", prices=[6800,11500,15200])
-
self.where{product == title}.each do |c|
-
if c.cached_product_variant_items.where{item_type == "duration"}.count>0 #assume non ucc
-
c.cached_product_variant_items.where{item_type == "duration"}.each_with_index{|pvi,i| pvi.update_column :amount, prices[i]}
-
elsif c.cached_product_variant_items.where{item_type == "ucc_domain"}.count>0 #assume ucc
-
c.cached_product_variant_items.where{item_type == "ucc_domain"}.each{|pvi|
-
i = pvi.value.to_i/365
-
price = if pvi.description=~/3 domains/i
-
prices[i-1][0]
-
elsif pvi.description=~/wildcard/i
-
prices[i-1][2]
-
else
-
prices[i-1][1]
-
end
-
pvi.update_column :amount, price
-
}
-
end
-
end
-
end
-
end
-
class CertificateApiRequest < ActiveRecord::Base
-
serialize :other_domains
-
validates :account_key, :secret_key, :product, :period, :server_count,
-
:server_software, :csr, :csr_obj, :is_customer_validated,
-
:dcv_email_address, :country, presence: true
-
-
#delete below when csr parser can obtain street and zip
-
validates :street_address_1, :postal_code, presence: true
-
#uncomment below when csr parser can obtain street and zip
-
# validates :street_address_1, presence: true, if: lambda{|c|c.csr_obj.street1.blank?}
-
# validates :postal_code, presence: true, if: lambda{|c|c.csr_obj.postal_code.blank?}
-
-
validates :other_domains, :domain, :common_names_flag, presence: false, unless: lambda{|c|c.product=~/[md|ucc]/}
-
validates :other_domains, presence: true, if: lambda{|c|c.product=~/[md|ucc]/ && c.csr_object.san.blank?}
-
validates :common_names_flag, presence: false, unless: lambda{|c|c.product=~/[md]/}
-
validates :incorporation_date, :registered_country_name , presence: true, if: lambda{|c|c.product=~/[ev]/}
-
validates :registered_locality_name, :registered_state_or_province_name, :registered_country_name,
-
:incorporation_date, :assumed_name, presence: false, unless: lambda{|c|c.product=~/[ev]/}
-
validates :organization_name, presence: true, if: lambda{|c|c.csr_obj.organization.blank?}
-
validates :locality_name, presence: true, if: lambda{|c|c.csr_obj.locality.blank?}
-
validates :state_or_province_name, presence: true, if: lambda{|c|c.csr_obj.state.blank?}
-
validates :dcv_email_address, :email_address, :contact_email_address, email: true
-
validates :business_category, format: /[bcd]/
-
validates :common_names_flag, format: /[01]/
-
-
ERROR_CODES = {
-
#"-1" => "Request was not made over https!",
-
"-2" => "'xxxx' is an unrecognised argument!",
-
"-3" => "The 'xxxx' argument is missing!",
-
"-4" => "The value of the 'xxxx' argument is invalid!",
-
"-5" => "The CSR's Common Name may NOT contain a wildcard!",
-
"-6" => "The CSR's Common Name MUST contain ONE wildcard!",
-
"-7" => "'xx' is not a valid ISO-3166 country!",
-
"-8" => "The CSR is missing a required field!",
-
"-9" => "The CSR is not valid Base-64 data!",
-
"-10" => "The CSR cannot be decoded!",
-
"-11" => "The CSR uses an unsupported algorithm!",
-
"-12" => "The CSR has an invalid signature!",
-
"-13" => "The CSR uses an unsupported key size!",
-
"-14" => "An unknown error occurred!",
-
"-15" => "Not enough credit!",
-
"-16" => "Permission denied! Contact SSL.com Support to enabled api access",
-
#"-17" => "Request used GET rather than POST!",
-
"-18" => "The CSR's Common Name may not be a Fully-Qualified Domain Name!",
-
"-19" => "The CSR's Common Name may not be an Internet-accessible IP Address!",
-
"-35" => "The CSR's Common Name may not be an IP Address!",
-
"-40" => "The CSR uses a key that is believed to have been compromised!"}
-
-
attribute :csr_obj, Csr.new
-
-
def csr=(csr)
-
self.csr_obj = Csr.new(body: csr)
-
write_attribute :csr, csr
-
end
-
-
def country=(country)
-
write_attribute :country, Country.find(c.csr_obj.country || country)
-
end
-
-
def server_software=(server_software)
-
write_attribute :server_software, ServerSoftware.find(server_software)
-
end
-
-
end
-
class CertificateContact < Contact
-
include Comparable
-
-
before_validation :set_roles
-
before_destroy :replace_with_default
-
after_save :set_one_default, if: 'contactable.is_a?SslAccount'
-
after_update :update_child_contacts, if: 'contactable.is_a?SslAccount'
-
-
validates :first_name, :last_name, :email, :phone, presence: true
-
validates :email, email: true
-
-
attr_accessor :update_parent
-
-
easy_roles :roles
-
-
-
def <=>(contact)
-
[first_name, last_name, email] <=> [contact.first_name, contact.last_name,
-
contact.email]
-
end
-
-
def to_digest_key
-
[first_name.capitalize, last_name.capitalize, email.downcase].join(",")
-
end
-
-
private
-
-
def update_child_contacts
-
Delayed::Job.enqueue SyncChildContactsJob.new(self.id)
-
end
-
-
def set_one_default
-
if saved_default
-
contactable.saved_contacts.where(saved_default: true).where.not(id: id)
-
.update_all(saved_default: false)
-
else
-
unless contactable.saved_contacts.where(saved_default: true).any?
-
self.update(saved_default: true)
-
end
-
end
-
end
-
-
# If saved/available contact is deleted, then update all child contacts to default contact
-
def replace_with_default
-
unless contactable.is_a?(CertificateContent)
-
found = contactable.saved_contacts.where(saved_default: true)
-
default = found.any? ? found.first : contactable.saved_contacts.first
-
if default
-
order_contacts.each do |c|
-
# do not update to default if default contact already exists for certificate content
-
exists = c.contactable.contacts_for_form_opt(:child).map(&:parent_id).uniq.include?(default.id)
-
exists ? c.destroy : c.update(parent_id: default.id)
-
end
-
Delayed::Job.enqueue SyncChildContactsJob.new(default.id) if order_contacts.any?
-
else
-
order_contacts.each {|c| c.update(parent_id: nil)}
-
end
-
end
-
end
-
end
-
1
class CertificateContent < ActiveRecord::Base
-
1
include V2MigrationProgressAddon
-
1
include Workflow
-
-
1
belongs_to :certificate_order, -> { unscope(where: [:workflow_state, :is_expired]) }, touch: true
-
1
has_one :ssl_account, through: :certificate_order
-
1
has_many :users, through: :certificate_order
-
1
belongs_to :server_software
-
1
has_one :csr, :dependent => :destroy
-
1
has_many :csrs, :dependent => :destroy
-
1
has_many :signed_certificates, through: :csr
-
1
has_one :registrant, as: :contactable, dependent: :destroy
-
1
has_one :locked_registrant, :as => :contactable
-
1
has_many :certificate_contacts, :as => :contactable
-
1
has_many :certificate_names, :dependent => :destroy do # used for dcv of each domain in a UCC or multi domain ssl
-
1
def validated
-
joins{domain_control_validations}.where{domain_control_validations.workflow_state=="satisfied"}.uniq
-
end
-
end
-
1
has_many :domain_control_validations, through: :certificate_names
-
1
has_many :url_callbacks, :dependent => :destroy, as: :callbackable
-
1
has_many :taggings, :dependent => :destroy, as: :taggable
-
1
has_many :tags, through: :taggings
-
1
belongs_to :ca
-
-
1
accepts_nested_attributes_for :certificate_contacts, :allow_destroy => true
-
1
accepts_nested_attributes_for :registrant, :allow_destroy => false
-
1
accepts_nested_attributes_for :csr, :allow_destroy => false
-
-
1
after_create :certificate_names_from_domains, unless: :certificate_names_created?
-
1
after_save :certificate_names_from_domains, unless: :certificate_names_created?
-
1
after_save :transfer_existing_contacts
-
1
before_destroy :preserve_certificate_contacts
-
-
1
before_create do |cc|
-
ref_number = cc.to_ref
-
cc.ref = ref_number
-
cc.label = ref_number
-
end
-
-
1
SIGNING_REQUEST_REGEX = /\A[\w\-\/\s\n\+=]+\Z/
-
1
MIN_KEY_SIZE = [2048, 3072, 4096, 6144, 8192] #thought would be 2048, be see
-
#http://groups.google.com/group/mozilla.dev.security.policy/browse_thread/thread/7ceb6dd787e20da3# for details
-
1
NOT_VALID_ISO_CODE="is not a valid 2 lettered ISO-3166 country code."
-
-
1
ADMINISTRATIVE_ROLE = 'administrative'
-
1
CONTACT_ROLES = %w(administrative billing technical validation)
-
-
1
RESELLER_FIELDS_TO_COPY = %w(first_name last_name
-
po_box address1 address2 address3 city state postal_code email phone ext fax)
-
-
# terms in this list that are submitted as domains for an ssl will be kicked back
-
1
BARRED_SSL_TERMS = %w(\A\. \.onion\z \.local\z)
-
-
1
TRADEMARKS = %w(.*?\.ssl\.com\z \Assl\.com\z .*?\.google\.com\z \Agoogle\.com\z .*?\.whatsapp\.com\z \Awhatsapp\.com\z
-
.*?\.?facebook\.com \Afacebook\.com\z
-
.*?\.apple\.com\z \Aapple\.com\z .*?\.microsoft\.com\z \Amicrosoft\.com\z .*?\.paypal\.com\z \Apaypal\.com\z
-
.*?\.mozilla\.com\z \Amozilla\.com\z .*?\.gmail\.com\z \Agmail\.com\z .*?\.goog\.com\z \Agoog\.com\z
-
.*?\.?github\.com .*?\.?amazon\.com .*?\.?cloudapp\.com amzn ssltools certchat .*?\.certlock\.com\z \Acertlock\.com\z
-
.*?\.10million\.org .*?\.android\.com\z \Aandroid\.com\z .*?\.aol\.com .*?\.azadegi\.com .*?\.balatarin\.com .*?\.?comodo\.com
-
.*?\.?digicert\.com .*?\.?yahoo\.com .*?\.?entrust\.com .*?\.?godaddy\.com .*?\.oracle\.com\z \Aoracle\.com\z
-
.*?\.?globalsign\.com .*?\.JanamFadayeRahbar\.com .*?\.?logmein\.com .*?\.mossad\.gov\.il
-
.*?\.?mozilla\.org .*?\.RamzShekaneBozorg\.com .*?\.SahebeDonyayeDigital\.com .*?\.skype\.com .*?\.startssl\.com
-
.*?\.?thawte\.com .*?\.torproject\.org .*?\.walla\.co\.il .*?\.windowsupdate\.com .*?\.wordpress\.com addons\.mozilla\.org
-
azadegi\.com Comodo\sRoot\sCA CyberTrust\sRoot\sCA DigiCert\sRoot\sCA Equifax\sRoot\sCA friends\.walla\.co\.il
-
GlobalSign\sRoot\sCA login\.live\.com my\.screenname\.aol\.com secure\.logmein\.com
-
Thawte\sRoot\sCA twitter\.com VeriSign\sRoot\sCA wordpress\.com www\.10million\.org www\.balatarin\.com
-
cia\.gov \.cybertrust\.com equifax\.com hamdami\.com mossad\.gov\.il sis\.gov\.uk
-
yahoo\.com login\.skype\.com mozilla\.org \.live\.com global\strustee)
-
-
1
WHITELIST = {492127=> %w(.*?\.ssl\.com\z \Assl\.com\z .*?\.certlock\.com\z \Acertlock\.com\z),
-
491981=> %w(.*?\.ssl\.com\z \Assl\.com\z .*?\.certlock\.com\z \Acertlock\.com\z),
-
# temporary for sandbox
-
474187=> %w(.*?\.ssl\.com\z \Assl\.com\z .*?\.certlock\.com\z \Acertlock\.com\z),
-
493588=> %w(.*?\.ssl\.com\z \Assl\.com\z .*?\.certlock\.com\z \Acertlock\.com\z),
-
# Nick (next 3)
-
492759=> %w(.*?\.ssl\.com\z \Assl\.com\z .*?\.certlock\.com\z \Acertlock\.com\z),
-
497080=> %w(.*?\.ssl\.com\z \Assl\.com\z .*?\.certlock\.com\z \Acertlock\.com\z),
-
474299=> %w(.*?\.ssl\.com\z \Assl\.com\z .*?\.certlock\.com\z \Acertlock\.com\z),
-
477317=> %w(.*?\.ssl\.com\z \Assl\.com\z .*?\.certlock\.com\z \Acertlock\.com\z),
-
464808=> %w(.*?\.ssl\.com\z \Assl\.com\z .*?\.certlock\.com\z \Acertlock\.com\z)}
-
-
1
DOMAIN_COUNT_OFFLOAD=50
-
-
#SSL.com=>Comodo
-
COMODO_SERVER_SOFTWARE_MAPPINGS = {
-
1
1=>-1, 2=>1, 3=>2, 4=>3, 5=>4, 6=>33, 7=>34, 8=>5,
-
9=>6, 10=>29, 11=>32, 12=>7, 13=>8, 14=>9, 15=>10,
-
16=>11, 17=>12, 18=>13, 19=>14, 20=>35, 21=>15,
-
22=>16, 23=>17, 24=>18, 25=>30, 26=>19, 27=>20, 28=>21,
-
29=>22, 30=>23, 31=>24, 32=>25, 33=>26, 34=>27, 35=>31, 36=>28, 37=>-1, 38=>-1, 39=>3}
-
-
1
INTRANET_IP_REGEX = /\A(127\.0\.0\.1)|(10.\d{,3}.\d{,3}.\d{,3})|(172\.1[6-9].\d{,3}.\d{,3})|(172\.2[0-9].\d{,3}.\d{,3})|(172\.3[0-1].\d{,3}.\d{,3})|(192\.168.\d{,3}.\d{,3})\z/
-
-
1
serialize :domains
-
-
1
validates_presence_of :server_software_id, :signing_request, # :agreement, # need to test :agreement out on reprocess and api submits
-
:if => "certificate_order_has_csr && !ajax_check_csr && Settings.require_server_software_w_csr_submit"
-
1
validates_format_of :signing_request, :with=>SIGNING_REQUEST_REGEX,
-
:message=> 'contains invalid characters.',
-
:if => :certificate_order_has_csr_and_signing_request
-
1
validate :domains_validation, if: :validate_domains?
-
1
validate :csr_validation, if: "new? && csr"
-
-
1
attr_accessor :additional_domains #used to html format results to page
-
1
attr_accessor :ajax_check_csr
-
1
attr_accessor :rekey_certificate
-
-
1
@@cli_domain = "https://sws.sslpki.com"
-
-
1
preference :reprocessing, default: false
-
-
1
CertificateNamesJob = Struct.new(:cc_id, :domains) do
-
1
def perform
-
CertificateContent.find_by_id(cc_id).certificate_names_from_domains
-
end
-
end
-
-
1
DcvSentNotifyJob = Struct.new(:cc_id, :host) do
-
1
def perform
-
cc = CertificateContent.find cc_id
-
co = cc.certificate_order
-
last_sent = unless co.certificate.is_ucc?
-
cc.csr.domain_control_validations.last_sent
-
else
-
cc.certificate_names.map{|cn| cn.last_sent_domain_control_validations.last}
-
.flatten.compact
-
end
-
unless last_sent.blank?
-
co.valid_recipients_list.each do |c|
-
OrderNotifier.dcv_sent(c, co, last_sent, host).deliver_now if host
-
end
-
end
-
end
-
end
-
-
1
def pre_validation(options)
-
if csr and !csr.sent_success #do not send if already sent successfully
-
options[:certificate_content] = self
-
if !self.infringement.empty? # possible trademark problems
-
OrderNotifier.potential_trademark(Settings.notify_address, certificate_order, self.infringement).deliver_now
-
elsif ca.blank?
-
certificate_order.apply_for_certificate(options)
-
end
-
if options[:host]
-
Delayed::Job.enqueue DcvSentNotifyJob.new(id, options[:host])
-
else
-
last_sent = unless certificate_order.certificate.is_ucc?
-
csr.domain_control_validations.last_sent
-
else
-
certificate_names.map {|cn| cn.last_sent_domain_control_validations.last}.flatten.compact
-
end
-
unless last_sent.blank?
-
certificate_order.valid_recipients_list.each do |c|
-
OrderNotifier.dcv_sent(c, certificate_order, last_sent).deliver!
-
end
-
end
-
end
-
end
-
end
-
-
1
workflow do
-
1
state :new do
-
1
event :submit_csr, :transitions_to => :csr_submitted
-
1
event :provide_info, :transitions_to => :info_provided
-
1
event :cancel, :transitions_to => :canceled
-
1
event :issue, :transitions_to => :issued
-
1
event :reset, :transitions_to => :new
-
1
event :validate, :transitions_to => :validated
-
1
event :pend_validation, :transitions_to => :pending_validation
-
end
-
-
1
state :csr_submitted do
-
1
event :issue, :transitions_to => :issued
-
1
event :provide_info, :transitions_to => :info_provided
-
1
event :reprocess, :transitions_to => :reprocess_requested
-
1
event :cancel, :transitions_to => :canceled
-
1
event :reset, :transitions_to => :new
-
end
-
-
1
state :info_provided do
-
1
event :validate, :transitions_to => :validated
-
1
event :submit_csr, :transitions_to => :csr_submitted
-
1
event :issue, :transitions_to => :issued
-
1
event :provide_contacts, :transitions_to => :contacts_provided
-
1
event :cancel, :transitions_to => :canceled
-
1
event :reset, :transitions_to => :new
-
1
event :pend_validation, :transitions_to => :pending_validation do |options={}|
-
pre_validation(options)
-
end
-
end
-
-
1
state :contacts_provided do
-
1
event :validate, :transitions_to => :validated
-
1
event :provide_contacts, transitions_to: :contacts_provided
-
1
event :submit_csr, :transitions_to => :csr_submitted
-
1
event :issue, :transitions_to => :issued
-
1
event :pend_issuance, :transitions_to => :pending_issuance
-
1
event :pend_validation, :transitions_to => :pending_validation do |options={}|
-
pre_validation(options)
-
end
-
1
event :cancel, :transitions_to => :canceled
-
1
event :reset, :transitions_to => :new
-
end
-
-
1
state :pending_validation do
-
1
event :issue, :transitions_to => :issued
-
1
event :validate, :transitions_to => :validated do
-
self.preferred_reprocessing = false if self.preferred_reprocessing?
-
end
-
1
event :pend_issuance, :transitions_to => :pending_issuance
-
1
event :cancel, :transitions_to => :canceled
-
1
event :reset, :transitions_to => :new
-
end
-
-
1
state :validated do
-
1
event :pend_validation, :transitions_to => :pending_validation
-
1
event :pend_issuance, :transitions_to => :pending_issuance
-
1
event :issue, :transitions_to => :issued
-
1
event :cancel, :transitions_to => :canceled
-
1
event :reset, :transitions_to => :new
-
end
-
-
1
state :pending_issuance do
-
1
event :pend_validation, :transitions_to => :pending_validation
-
1
event :pend_issuance, :transitions_to => :pending_issuance
-
1
event :validate, :transitions_to => :validated
-
1
event :issue, :transitions_to => :issued
-
1
event :cancel, :transitions_to => :canceled
-
1
event :reset, :transitions_to => :new
-
end
-
-
1
state :issued do
-
1
event :reprocess, :transitions_to => :csr_submitted
-
1
event :pend_issuance, :transitions_to => :pending_issuance
-
1
event :validate, :transitions_to => :validated
-
1
event :cancel, :transitions_to => :canceled
-
1
event :revoke, :transitions_to => :revoked
-
1
event :issue, :transitions_to => :issued
-
1
event :reset, :transitions_to => :new
-
end
-
-
1
state :canceled
-
-
1
state :revoked do
-
1
event :revoke, :transitions_to => :revoked
-
end
-
end
-
-
1
after_initialize do
-
if new_record?
-
self.ajax_check_csr ||= false
-
self.signing_request ||= ""
-
end
-
end
-
-
1
def add_ca(ssl_account)
-
# dtnt comodo chained is 492703
-
# 499740 using Azure. Remove once we are in Azure
-
unless [467564,16077,204730,492703,21291,499740,490782].include?(ssl_account.id)
-
self.ca = (self.certificate.cas.ssl_account_or_general_default(ssl_account)).last if ca.blank? and certificate
-
end
-
end
-
-
1
OtherDcvsSatisyJob = Struct.new(:ssl_account,:new_certificate_name) do
-
1
def perform
-
ssl_account.other_dcvs_satisfy_domain(new_certificate_name)
-
end
-
end
-
-
1
def certificate_names_from_domains(domains=nil)
-
unless (certificate.is_single? or certificate.is_wildcard?) and certificate_names.count > 0
-
domains ||= all_domains
-
(domains-certificate_names.find_by_domains(domains).pluck(:name)).each do |domain|
-
unless domain=~/,/
-
cn_domain = certificate.is_single? ? CertificateContent.non_wildcard_name(domain,true) : domain
-
new_certificate_name=certificate_names.find_or_create_by(name: cn_domain.downcase)
-
new_certificate_name.update_column(:is_common_name, csr.try(:common_name)==domain)
-
new_certificate_name.candidate_email_addresses # start the queued job running
-
Delayed::Job.enqueue OtherDcvsSatisyJob.new(ssl_account,new_certificate_name) if ssl_account && certificate.is_server?
-
end
-
end
-
end
-
# Auto adding domains in case of certificate order has been included into some groups.
-
NotificationGroup.auto_manage_cert_name(self, 'create')
-
end
-
-
1
def all_domains_validated?
-
(certificate_names.pluck(:id) - certificate_names.validated.pluck(:id)).empty?
-
end
-
-
1
def signed_certificate
-
signed_certificates.last
-
end
-
-
1
def sslcom_ca_request
-
SslcomCaRequest.where(username: self.label).first
-
end
-
-
1
def pkcs7
-
sslcom_ca_request.pkcs7
-
end
-
-
1
def x509_certificates
-
sslcom_ca_request.try(:x509_certificates)
-
end
-
-
1
def certificate_chain
-
sslcom_ca_request.certificate_chain
-
end
-
-
# :with_tags (default), :x509, :without_tags
-
1
def ejbca_certificate_chain(options={format: :with_tags})
-
chain=sslcom_ca_request
-
xcert=Certificate.xcert_certum(chain.x509_certificates.last)
-
certs=chain.x509_certificates
-
if options[:format]==:objects
-
xcert ? certs[0..-2]<<OpenSSL::X509::Certificate.new(SignedCertificate.enclose_with_tags(xcert)) : certs
-
elsif options[:format]==:without_tags
-
certs=chain.certificate_chain
-
xcert ? certs[0..-2]<<SignedCertificate.remove_begin_end_tags(xcert).chop : certs
-
else
-
xcert ? certs[0..-2].map(&:to_s)<<SignedCertificate.enclose_with_tags(xcert) : certs.map(&:to_s)
-
end unless chain.blank?
-
end
-
-
1
def certificate
-
certificate_order.try :certificate
-
end
-
-
# validate all certificate_names based on a previous validation
-
1
def validate_via_cname
-
certificate_names.each{|cn|cn.validate_via_cname}
-
ca=csrs.map{|c|c.signed_certificates.map(&:created_at)}.first.first
-
domain_control_validations.update_all responded_at: ca, created_at: ca, updated_at: ca
-
end
-
-
1
def self.cli_domain=(cli_domain)
-
@@cli_domain=cli_domain
-
end
-
-
1
def cli_domain
-
@@cli_domain
-
end
-
-
1
def domains=(names)
-
unless names.blank?
-
names = names.split(Certificate::DOMAINS_TEXTAREA_SEPARATOR).flatten.reject{|d|d.blank?}.map(&:downcase).uniq
-
end
-
write_attribute(:domains, names)
-
end
-
-
# are any of the sub/domains trademarks?
-
1
def infringement
-
return ca_id.blank? ? [] : all_domains.map{|domain|domain if (TRADEMARKS-
-
(ssl_account and WHITELIST[ssl_account.id] ? WHITELIST[ssl_account.id] : [])).any?{|trademark|
-
domain.downcase =~ Regexp.new(trademark, Regexp::IGNORECASE)}}.compact
-
end
-
-
1
def self.infringers
-
CertificateContent.find_all{|cc|!cc.infringement.empty?}
-
end
-
-
1
def domains
-
cur_domains = read_attribute(:domains)
-
if cur_domains.kind_of?(Array) && cur_domains.flatten==["0"]
-
[]
-
else
-
parse_unique_domains(cur_domains)
-
end
-
end
-
-
1
def additional_domains=(html_domains)
-
self.domains=html_domains
-
end
-
-
1
def additional_domains
-
domains.join("\ ") unless domains.blank?
-
end
-
-
1
def all_domains
-
parse_unique_domains(
-
(domains.blank? ? [] : domains) + [csr.try(:all_names)] + certificate_names.map(&:name)
-
)
-
end
-
-
1
def certificate_names_by_domains
-
certificate_names.find_by_domains(all_domains).compact
-
end
-
-
1
def callback(packaged_cert,options={})
-
uc = unless options.blank?
-
UrlCallback.new(options)
-
else
-
url_callbacks.last
-
end
-
uc.perform_callback(certificate_hook:packaged_cert) unless uc.blank?
-
end
-
-
1
def dcv_suffix
-
ca_id ? "ssl.com" : "comodoca.com"
-
end
-
-
1
def manually_validate_cname
-
(certificate_names-certificate_names.validated).each do |name|
-
p [name.name,name.dcv_verify("cname",ignore_unique_value: true)]
-
end
-
end
-
-
1
def dcv_domains(options)
-
i = 0
-
dcvs = [] # bulk insert of dcv
-
cn_ids = [] # need to touch certificate_names to bust cache since bulk insert skips callbacks
-
certificate_names.find_by_domains(options[:domains].keys).
-
includes(:validated_domain_control_validations).each do |name|
-
cn_ids << name.id
-
k, v = name.name, options[:domains][name.name]
-
cur_email = options[:emails] ? options[:emails][k] : nil
-
-
case v["dcv"]
-
when /https?/i, /cname/i
-
dcv = name.validated_domain_control_validations.last
-
if dcv.blank?
-
dcv = name.domain_control_validations.new(
-
dcv_method: v["dcv"],
-
candidate_addresses: cur_email,
-
failure_action: v["dcv_failure_action"]
-
)
-
dcvs << dcv
-
end
-
-
if (v["dcv_failure_action"]=="remove" || options[:dcv_failure_action]=="remove")
-
found = dcv.verify_http_csr_hash
-
self.domains.delete(k) unless found
-
end
-
else
-
if DomainControlValidation.approved_email_address? CertificateName.candidate_email_addresses(
-
name.non_wildcard_name), v["dcv"]
-
dcvs << name.domain_control_validations.new(dcv_method: "email", email_address: v["dcv"],
-
failure_action: v["dcv_failure_action"],
-
candidate_addresses: CertificateName.candidate_email_addresses(
-
name.non_wildcard_name))
-
end
-
end
-
i+=1
-
end
-
DomainControlValidation.import dcvs
-
CertificateName.where(id: cn_ids).update_all updated_at: DateTime.now
-
end
-
-
1
def signing_request=(signing_request)
-
write_attribute(:signing_request, signing_request)
-
if (signing_request=~SIGNING_REQUEST_REGEX)==0
-
unless self.create_csr(:body=>signing_request)
-
logger.error "error #{self.model_and_id}#signing_request saving #{signing_request}"
-
end
-
end
-
end
-
-
1
def migrated_from
-
v=V2MigrationProgress.find_by_migratable(self, :all)
-
v.map(&:source_obj) if v
-
end
-
-
1
def show_validation_view?
-
if new? || csr_submitted?
-
false
-
else
-
true
-
end
-
end
-
-
1
def validation_type
-
(signed_certificate || certificate).validation_type
-
end
-
-
1
CONTACT_ROLES.each do |role|
-
4
define_method("#{role}_contacts") do
-
certificate_contacts(true).select{|c|c.has_role? role}
-
end
-
-
4
define_method("#{role}_contact") do
-
send("#{role}_contacts").last
-
end
-
end
-
-
1
def cached_certificate_order
-
CertificateOrder.unscoped.find_by_id(Rails.cache.fetch("#{cache_key}/cached_certificate_order")do
-
certificate_order.id
-
end)
-
end
-
-
1
def expired?
-
csr.signed_certificate.expired? if csr.try(:signed_certificate)
-
end
-
-
1
def expiring?
-
if csr.try(:signed_certificate)
-
ed=csr.signed_certificate.expiration_date
-
ed < Settings.expiring_threshold.days.from_now unless ed.blank?
-
end
-
end
-
-
#finds or creates a certificate lookup
-
1
def self.public_cert(cn,port=443)
-
return nil if is_intranet?
-
context = OpenSSL::SSL::SSLContext.new
-
begin
-
timeout(10) do
-
tcp_client = TCPSocket.new cn, port
-
ssl_client = OpenSSL::SSL::SSLSocket.new tcp_client, context
-
ssl_client.connect
-
cert=ssl_client.peer_cert
-
CertificateLookup.create(
-
certificate: cert.to_s,
-
serial: cert.serial,
-
expires_at: cert.not_after,
-
common_name: cn) unless CertificateLookup.find_by_serial(cert.serial)
-
cert
-
end
-
rescue Exception=>e
-
nil
-
end
-
end
-
-
1
def comodo_server_software_id
-
COMODO_SERVER_SOFTWARE_MAPPINGS[server_software ? server_software.id : -1]
-
end
-
-
1
def common_name
-
(certificate_names.find_by_is_common_name(true).try(:name) ||
-
certificate_names.last.try(:name) || csr.try(:common_name)).downcase
-
end
-
-
1
def has_all_contacts?
-
if Contact.optional_contacts?
-
if certificate_order.certificate.is_dv? and Settings.exempt_dv_contacts
-
true
-
else
-
certificate_contacts.any?
-
end
-
else
-
CertificateContent::CONTACT_ROLES.all? do |role|
-
send "#{role}_contact"
-
end
-
end
-
end
-
-
1
def domains_and_common_name
-
domains.flatten.uniq+[certificate_order.common_name]
-
end
-
-
1
def self.is_tld?(name)
-
DomainNameValidator.valid?(name.downcase) if name
-
end
-
-
1
def self.is_intranet?(name)
-
(name=~/\d{,3}\.\d{,3}\.\d{,3}\.\d{,3}/ ? is_intranet_ip?(name) : !is_tld?(name)) if name
-
end
-
-
1
def self.is_intranet_ip?(name)
-
!!(name=~INTRANET_IP_REGEX) if name
-
end
-
-
1
def self.is_ip_address?(name)
-
name.index(/\A(?:[0-9]{1,3}\.){3}[0-9]{1,3}\z/)==0 if name
-
end
-
-
1
def self.is_server_name?(name)
-
name.index(/\./)==nil if name
-
end
-
-
1
def self.top_level_domain(name)
-
if is_fqdn?(name)
-
name=~(/(?:.*?\.)(.+)/)
-
$1
-
end
-
end
-
-
# TODO rename this to include www function, or break this up into 2 functions
-
1
def self.non_wildcard_name(name,remove_www=false)
-
name=name.gsub(/\A\*\./, "").downcase unless name.blank?
-
remove_www ? name.gsub("www.", "") : name
-
end
-
-
1
def self.is_fqdn?(name)
-
unless is_ip_address?(name) && is_server_name?(name)
-
name.index(/\A[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?\z/ix)==0
-
end if name
-
end
-
-
1
def to_ref
-
cc = certificate_order.certificate_contents.where.not(id: nil)
-
index = if cc.empty?
-
0
-
else
-
cc_ref=cc.order(:created_at).last.ref
-
cc_ref.blank? ? 0 : cc_ref.split('-').last.to_i + 1
-
end
-
"#{certificate_order.ref}-#{index}"
-
end
-
-
1
def contacts_for_form_opt(type=nil)
-
certificate_contact_compatibility
-
case type
-
when :custom # contacts that are NOT duplicated from saved contacts
-
certificate_contacts(true).select{|c| c.parent_id.nil? && c.type=='CertificateContact'}
-
when :child # contacts that were duplicated from saved contacts
-
certificate_contacts(true).select{|c| !c.parent_id.nil? && c.type=='CertificateContact'}
-
when :saved # saved contacts for the team
-
ssl_account.saved_contacts.select{|c| c.type=='CertificateContact'}
-
when :selected # contacts, BOTH child and custom
-
certificate_contacts(true).select{|c| c.type=='CertificateContact'}
-
else
-
[]
-
end
-
end
-
-
1
def contacts_for_form
-
certificate_contact_compatibility
-
unless self.certificate_contacts.blank?
-
list = CertificateContent::CONTACT_ROLES.map{|role|self.send "#{role}_contact"}.compact
-
roles = list.map(&:roles).flatten.uniq
-
CertificateContent::CONTACT_ROLES.each do |r|
-
unless roles.include? r
-
new_contact = CertificateContact.new(
-
contactable: self, country: self.registrant.try(:country), roles: [r]
-
)
-
r == 'administrative' ? list.unshift(new_contact) : list.push(new_contact)
-
end
-
end
-
list
-
else
-
[].tap{|c_tmp|CertificateContent::CONTACT_ROLES.each {|r|
-
c_tmp << CertificateContact.new(contactable: self, country: self.registrant.try(:country), roles: [r])}}
-
end
-
end
-
-
1
def emergency_contact_emails
-
(certificate_order.ssl_account.get_account_admins.map(&:email) +
-
[certificate_order.ssl_account.get_account_owner.email] +
-
administrative_contacts.map(&:email) +
-
technical_contacts.map(&:email)).compact.uniq
-
end
-
-
# each domain needs to go through this
-
1
def domain_validation(domain)
-
is_wildcard = certificate_order.certificate.allow_wildcard_ucc?
-
is_ucc = certificate_order.certificate.is_ucc?
-
is_server = certificate_order.certificate.is_server?
-
is_premium_ssl = certificate_order.certificate.is_premium_ssl?
-
invalid_chars_msg = "#{domain} has invalid characters. Only the following characters
-
are allowed [A-Za-z0-9.-#{'*' if(is_ucc || is_wildcard)}] in the domain or subject"
-
if CertificateContent.is_ip_address?(domain) && false # CertificateContent.is_intranet?(domain)
-
errors.add(:domain, " #{domain} must be an Internet-accessible IP Address")
-
else
-
if is_server
-
#errors.add(:signing_request, 'is missing the organization (O) field') if csr.organization.blank?
-
asterisk_found = (domain=~/\A\*\./)==0
-
if ((!is_ucc && !is_wildcard) || is_premium_ssl) && asterisk_found
-
errors.add(:domain, "cannot begin with *. since the order does not allow wildcards")
-
elsif certificate_order.certificate.is_dv? && CertificateContent.is_ip_address?(domain)
-
errors.add(:domain, "#{domain} was determined to be for an ip address. This is only allowed on OV or EV ssl orders.")
-
elsif !!(domain=~Regexp.new("\\.("+Country::BLACKLIST.join("|")+")$",true))
-
errors.add(:domain, "#{domain} is a restricted tld")
-
end
-
errors.add(:domain, invalid_chars_msg) unless
-
domain_validation_regex(is_wildcard || (is_ucc && !is_premium_ssl), domain.gsub(/\x00/, ''))
-
BARRED_SSL_TERMS.each do |barred|
-
errors.add(:domain, "#{domain} contains non-compliant form") if domain =~ Regexp.new(barred)
-
end
-
errors.add(:domain, "#{domain} contains more than one * character") if (domain.scan /\*/).count > 1
-
errors
-
end
-
end
-
end
-
-
1
def uniq_certificate_names
-
certificate_names.pluck(:name).uniq.map{|c|certificate_names.order("created_at asc").find_by_name(c).id}
-
end
-
-
1
def dedupe_certificate_names
-
CertificateName.delete(certificate_names.pluck(:id) - uniq_certificate_names)
-
end
-
-
# 1- End Entity Profile : DV_SERVER_CERT_EE and Certificate Profile: DV_RSA_SERVER_CERT
-
#
-
# Subject DN
-
#
-
# CN (Common name) - Required
-
#
-
# Subject Alternative Name
-
#
-
# dNSName - It could be multiple but atleast one is required
-
#
-
# 2- End Entity Profile : OV_SERVER_CERT_EE and Certificate Profile: OV_RSA_SERVER_CERT
-
#
-
# Subject DN
-
#
-
# CN (Common name) - Required
-
# OU (Organizational Unit) - Optional
-
# O (Organization) - Required
-
# L (Locality) - Optional
-
# ST (State or Province) - Optional
-
# C (Country) - Required
-
# postalCode - Optional
-
# postalAddress - Optional
-
# streetAddress - Optional
-
#
-
# Subject Alternative Name
-
#
-
# dNSName - It could be multiple but atleast one is required
-
#
-
# 3- End Entity Profile : EV_SERVER_CERT_EE and Certificate Profile: EV_RSA_SERVER_CERT
-
#
-
# Subject DN
-
#
-
# CN (Common name) - Required
-
# OU (Organizational Unit) - Optional
-
# O (Organization) - Required
-
# L (Locality) - Optional
-
# ST (State or Province) - Optional
-
# C (Country) - Required
-
# postalCode - Optional
-
# postalAddress - Optional
-
# streetAddress - Optional
-
# 2.5.4.15 (businessCategory)- Required
-
# serialNumber - Required
-
# 1.3.6.1.4.1.311.60.2.1.1 (Jurisdiction Locality) - Optional
-
# 1.3.6.1.4.1.311.60.2.1.2 (Jurisdiction State or Province) - Optional
-
# 1.3.6.1.4.1.311.60.2.1.3 (Jurisdiction Country) - Required
-
#
-
# Subject Alternative Name
-
#
-
# dNSName - It could be multiple but atleast one is required
-
#
-
# 4- End Entity Profile : EV_CS_CERT_EE and Certificate Profile: EV_RSA_CS_CERT
-
#
-
# Subject DN
-
#
-
# CN (Common name) - Required
-
# OU (Organizational Unit) - Optional
-
# O (Organization) - Required
-
# L (Locality) - Optional
-
# ST (State or Province) - Optional
-
# C (Country) - Required
-
# postalCode - Optional
-
# postalAddress - Optional
-
# streetAddress - Optional
-
# 2.5.4.15 (businessCategory)- Required
-
# serialNumber - Required
-
# 1.3.6.1.4.1.311.60.2.1.1 (Jurisdiction Locality) - Optional
-
# 1.3.6.1.4.1.311.60.2.1.2 (Jurisdiction State or Province) - Optional
-
# 1.3.6.1.4.1.311.60.2.1.3 (Jurisdiction Country) - Required
-
#
-
# Subject Alternative Name
-
#
-
# This extension is not required for this profile
-
#
-
# 5- End Entity Profile : CS_CERT_EE and Certificate Profile: RSA_CS_CERT
-
#
-
# Subject DN
-
#
-
# CN (Common name) - Required
-
# OU (Organizational Unit) - Optional
-
# O (Organization) - Required
-
# streetAddress - Optional
-
# L (Locality) - Optional
-
# ST (State or Province) - Optional
-
# postalCode - Optional
-
# C (Country) - Required
-
#
-
# Subject Alternative Name
-
#
-
#
-
# Note:-
-
#
-
# Subject DN format : "subject_dn": "CN=saad.com,O=SSL.COM,C=US". The names in open and closing parenthisis are just for description e.g. CN (common name). Here (common name) is for description. You only need to pass CN in subject DN. Those names that do not have any parenthisis will be passed as it is in subject DN.
-
# Subject alternative name format : "subject_alt_name": "dNSName=foo2.bar.com, dNSName=foo2.bar.com"
-
-
1
def locked_subject_dn
-
dn = []
-
if locked_registrant
-
dn << "CN=#{locked_registrant.company_name}" unless locked_registrant.company_name.blank?
-
if !locked_registrant.company_name.blank? and (!locked_registrant.city.blank? or !locked_registrant.state.blank?)
-
dn << "O=#{locked_registrant.company_name}"
-
end
-
dn << "OU=#{locked_registrant.department}" unless locked_registrant.department.blank?
-
dn << "L=#{locked_registrant.city}" unless locked_registrant.city.blank?
-
dn << "ST=#{locked_registrant.state}" unless locked_registrant.state.blank?
-
dn << "C=#{locked_registrant.country}" unless locked_registrant.country.blank?
-
# dn << "postalCode=#{locked_registrant.postal_code}" unless locked_registrant.postal_code.blank?
-
dn.map{|d|d.gsub(/\\/,'\\\\').gsub(',','\,')}.join(",")
-
end
-
end
-
-
1
def subject_dn(options={})
-
cert = options[:certificate] || self.certificate
-
dn=certificate.is_server? ? ["CN=#{options[:common_name] || common_name}"] : []
-
dn << "emailAddress=#{certificate_order.get_recipient.email}" if certificate.is_smime? && certificate_order.get_recipient.email
-
if certificate.is_smime_or_client? and !certificate.is_client_basic?
-
person=certificate_order.locked_recipient
-
dn << "CN=#{[person.first_name,person.last_name].join(" ").strip}"
-
end
-
if locked_registrant and !(options[:mapping] ? options[:mapping].try(:profile_name) =~ /DV/ : cert.is_dv?)
-
# if ev or ov order, must have locked registrant
-
dn= ["CN=#{locked_registrant.company_name}"] if certificate.is_code_signing?
-
org=locked_registrant.company_name
-
ou=locked_registrant.department
-
state=locked_registrant.state
-
city=locked_registrant.city
-
country=locked_registrant.country
-
postal_code=locked_registrant.postal_code
-
postal_address=locked_registrant.po_box
-
street_address=
-
[locked_registrant.address1,locked_registrant.address2,locked_registrant.address3].join(" ")
-
dn << "O=#{org}" if !org.blank? and (!city.blank? or !state.blank?)
-
dn << "OU=#{ou}" unless ou.blank?
-
dn << "OU=#{locked_registrant.special_fields["entity_code"]}" if certificate.is_naesb? and
-
!certificate_order.locked_registrant.special_fields.blank?
-
dn << "C=#{country}"
-
dn << "L=#{city}" unless city.blank?
-
dn << "ST=#{state}" unless state.blank?
-
# dn << "postalCode=#{postal_code}" unless postal_code.blank?
-
# dn << "postalAddress=#{postal_address}" unless postal_address.blank?
-
# dn << "streetAddress=#{street_address}" unless street_address.blank?
-
if cert.is_ev? or cert.is_evcs?
-
dn << "serialNumber=#{locked_registrant.company_number}"
-
dn << "2.5.4.15=#{locked_registrant.business_category}"
-
dn << "1.3.6.1.4.1.311.60.2.1.1=#{locked_registrant.incorporation_city}" unless
-
locked_registrant.incorporation_city.blank?
-
dn << "1.3.6.1.4.1.311.60.2.1.2=#{locked_registrant.incorporation_state}" unless
-
locked_registrant.incorporation_state.blank?
-
dn << "1.3.6.1.4.1.311.60.2.1.3=#{locked_registrant.incorporation_country}"
-
end
-
end
-
dn << options[:custom_fields] if options[:custom_fields]
-
dn.map{|d|d.gsub(/\\/,'\\\\').gsub(',','\,')}.join(",")
-
end
-
-
1
def cached_csr_public_key_sha1
-
Rails.cache.fetch("#{cache_key}/cached_csr_public_key_sha1") do
-
csr.public_key_sha1
-
end
-
end
-
-
1
def cached_csr_public_key_md5
-
Rails.cache.fetch("#{cache_key}/cached_csr_public_key_md5") do
-
csr.public_key_md5
-
end
-
end
-
-
1
def csr_certificate_name
-
begin
-
if csr and certificate_names.find_by_name(csr.common_name).blank?
-
certificate_names.update_all(is_common_name: false)
-
certificate_names.create(name: csr.common_name, is_common_name: true)
-
end
-
rescue
-
end
-
end
-
-
1
def preserve_certificate_contacts
-
cc = certificate_order.certificate_contents.where.not(id: id).last
-
unless cc.nil?
-
certificate_contacts.update_all(contactable_id: cc.id)
-
end
-
end
-
-
1
private
-
-
1
def certificate_contact_compatibility
-
if Contact.optional_contacts? # optional contacts ENABLED
-
# contacts created from saved contacts
-
certificate_contacts(true).where(type: 'CertificateContact')
-
.where.not(parent_id: nil).group_by(&:parent_id).each do |c_group|
-
group = c_group.second
-
if group.count > 1
-
ids = group.map(&:id)
-
certificate_contacts(true).find(ids.shift).update(roles: Contact.find(c_group.first).roles)
-
certificate_contacts(true).where(id: ids).destroy_all
-
end
-
end
-
# custom contacts, only created for this certificate content
-
# convert 4 identical contacts into one w/role 'administrative'
-
custom_contacts = certificate_contacts(true).where(type: 'CertificateContact', parent_id: nil)
-
custom_contacts.each do |c|
-
list = custom_contacts.where(c.attributes.keep_if {|k,_| Contact::SYNC_FIELDS_REQUIRED.include? k.to_sym})
-
if list.count > 1
-
found = list.first
-
found.update(roles: ['administrative'])
-
list.where.not(id: found.id).destroy_all
-
end
-
end
-
else # Optional contacts DISABLED
-
keep = []
-
updated = 0
-
all = certificate_contacts(true).where(type: 'CertificateContact')
-
CertificateContent::CONTACT_ROLES.each do |role|
-
found = certificate_contacts(true).where(type: 'CertificateContact')
-
.where("roles LIKE ?", "%#{role}%")
-
if found.any?
-
update = found.first
-
found = all - [update]
-
if update.roles.count > 1
-
update.update(roles: [role])
-
updated += 1
-
end
-
keep << update
-
end
-
end
-
if updated > 0
-
self.update(billing_checkbox: 0, validation_checkbox: 0, technical_checkbox: 0)
-
end
-
all.where.not(id: keep.map(&:id)).destroy_all
-
end
-
end
-
-
1
def validate_domains?
-
(new? && (domains.blank? || errors[:domain].any?)) || !rekey_certificate.blank?
-
end
-
-
1
def certificate_names_created?
-
self.reload
-
return false if domains.blank? && !certificate_name_from_csr?
-
new_domains = parse_unique_domains(domains)
-
current_domains = parse_unique_domains(certificate_names.pluck(:name))
-
common = current_domains & new_domains
-
common.length == new_domains.length && (current_domains.length == new_domains.length)
-
end
-
-
1
def certificate_name_from_csr?
-
certificate_names.count == 1 &&
-
csr.common_name &&
-
certificate_names.first.name == csr.common_name &&
-
certificate_names.first.is_common_name
-
end
-
-
1
def parse_unique_domains(target_domains)
-
return [] if target_domains.blank?
-
target_domains.flatten.compact.map(&:downcase).map(&:strip).reject(&:blank?).uniq
-
end
-
-
1
def domains_validation
-
unless all_domains.blank?
-
all_domains.each do |domain|
-
domain_validation(domain)
-
end
-
end
-
self.rekey_certificate = false unless domains.blank?
-
end
-
-
1
def csr_validation
-
allow_wildcard_ucc=certificate_order.certificate.allow_wildcard_ucc?
-
is_wildcard = certificate_order.certificate.is_wildcard?
-
is_ucc = certificate_order.certificate.is_ucc?
-
is_server = certificate_order.certificate.is_server?
-
if csr.common_name.blank?
-
errors.add(:signing_request, 'is missing the common name (CN) field or is invalid and cannot be parsed')
-
elsif !csr.verify_signature
-
errors.add(:signing_request, 'has an invalid signature')
-
else
-
if is_server
-
asterisk_found = (csr.common_name=~/\A\*\./)==0
-
if is_wildcard && !asterisk_found
-
errors.add(:signing_request, "is wildcard certificate order, so it must begin with *.")
-
elsif ((!(is_ucc && allow_wildcard_ucc) && !is_wildcard)) && asterisk_found
-
errors.add(:signing_request, "cannot begin with *. since the order does not allow wildcards")
-
elsif !DomainNameValidator.valid?(csr.common_name)
-
errors.add(:signing_request, "common name field is invalid")
-
end
-
end
-
errors.add(:signing_request, "must be any of the following #{MIN_KEY_SIZE.join(', ')} key sizes.
-
Please submit a new certificate signing request with the proper key size.") if
-
csr.sig_alg=~/WithRSAEncryption/i && (csr.strength.blank? || !MIN_KEY_SIZE.include?(csr.strength))
-
#errors.add(:signing_request,
-
# "country code '#{csr.country}' #{NOT_VALID_ISO_CODE}") unless
-
# Country.accepted_countries.include?(csr.country)
-
end
-
end
-
-
# This validates each domain entry in the CN and SAN fields
-
1
def domain_validation_regex(is_wildcard, domain)
-
invalid_chars = "[^\\s\\n\\w\\.\\x00\\-#{'\\*' if is_wildcard}]"
-
domain.index(Regexp.new(invalid_chars))==nil and
-
domain.index(/\.\.+/)==nil and domain.index(/\A\./)==nil and
-
domain.index(/[^\w]\z/)==nil and domain.index(/\A[^\w\*]/)==nil and
-
is_wildcard ? (domain.index(/(\w)\*/)==nil and
-
domain.index(/(\*)[^\.]/)==nil) : true
-
end
-
-
1
def certificate_order_has_csr
-
['true',true].any?{|t|t==certificate_order.try(:has_csr)}
-
end
-
-
1
def certificate_order_has_csr_and_signing_request
-
certificate_order_has_csr && !signing_request.blank?
-
end
-
-
1
def delete_duplicate_contacts
-
CONTACT_ROLES.each do |role|
-
contacts = send "#{role}_contacts"
-
if contacts.count > 1
-
contacts.shift
-
contacts.each do |c|
-
c.destroy
-
end
-
end
-
end
-
true
-
end
-
-
1
def transfer_existing_contacts
-
certificate_order.certificate_contacts
-
.where.not(contactable_id: id)
-
.update_all(contactable_id: id)
-
-
Contact.clear_duplicate_co_contacts(certificate_order)
-
-
if certificate_contacts.any? && info_provided?
-
provide_contacts!
-
end
-
end
-
end
-
class CertificateEnrollmentRequest < ActiveRecord::Base
-
include Filterable
-
include Sortable
-
-
attr_accessor :additional_domains, :ssl_slug
-
-
enum status: { pending: 1, approved: 5, rejected: 10 }
-
-
belongs_to :ssl_account
-
belongs_to :user
-
belongs_to :certificate
-
belongs_to :order
-
-
serialize :domains
-
-
validates :ssl_account, presence: true
-
-
def self.index_filter(params)
-
filters = {}
-
p = params
-
filters[:id] = { '=' => p[:id] } unless p[:id].blank?
-
result = filter(filters)
-
result
-
end
-
end
-
# This class looks up Web ssl certs on domains and provides
-
# a reference for expirations for both csrs and signed certificates
-
-
class CertificateLookup < ActiveRecord::Base
-
has_many :site_checks
-
has_many :csrs
-
has_many :signed_certificates
-
-
scope :most_recent_expiring, lambda{|start, finish|
-
find_by_sql("select * from certificate_lookups as c where expires_at between '#{start}' AND '#{finish}' AND created_at = ( select max(created_at) from certificate_lookups where common_name like c.common_name )")}
-
-
# scan all certs in the Web and update csrs and signed_certificates. Uniqueness
-
# of installed certs on the Web will be determined by serial number
-
def self.scan_certificates(cutoff_date=Date.today)
-
(Csr.pluck(:common_name)+SignedCertificate.pluck(:common_name)).uniq.each do |cn|
-
c=CertificateLookup.find_by_common_name(cn.gsub("*.", "www."))
-
if c.blank? || c.created_at < cutoff_date
-
sc=SiteCheck.new(url: cn, verify_trust: false)
-
if sc.create_certificate_lookup
-
sc.certificate_lookup.update_references(cn)
-
end
-
end
-
end
-
end
-
-
# update references to all csrs and signed certs to this lookup
-
def update_references(cn=self.common_name)
-
Csr.find_all_by_common_name(cn).each {|csr|
-
csr.update_attribute(:certificate_lookup_id, id)}
-
SignedCertificate.find_all_by_common_name(cn).each {|sc|
-
sc.update_attribute(:certificate_lookup_id, id)}
-
end
-
-
def lookup
-
SiteCheck.new url: common_name, verify_trust: false
-
end
-
end
-
# Represents a domain name or ip address to be secured by a UCC or Multi domain SSL
-
require 'resolv'
-
-
class CertificateName < ActiveRecord::Base
-
belongs_to :certificate_content
-
has_many :signed_certificates, through: :certificate_content
-
has_many :caa_checks, as: :checkable
-
has_many :ca_certificate_requests, as: :api_requestable, dependent: :destroy
-
has_many :ca_dcv_requests, as: :api_requestable, dependent: :destroy
-
has_many :ca_dcv_resend_requests, as: :api_requestable, dependent: :destroy
-
has_many :validated_domain_control_validations, -> { where(workflow_state: "satisfied")},
-
class_name: "DomainControlValidation"
-
has_many :last_sent_domain_control_validations, -> { where{email_address !~ 'null'}},
-
class_name: "DomainControlValidation"
-
has_many :domain_control_validations, dependent: :destroy do
-
def last_sent
-
where{email_address !~ 'null'}.last
-
end
-
-
def last_emailed
-
where{(email_address !~ 'null') & (dcv_method >> [nil,'email'])}.last
-
end
-
-
def last_method
-
where{dcv_method >> ['http','https','email','cname']}.last
-
end
-
-
def validated
-
where{workflow_state=="satisfied"}.last
-
end
-
end
-
has_many :notification_groups_subjects, as: :subjectable
-
has_many :notification_groups, through: :notification_groups_subjects
-
-
attr_accessor :csr
-
-
scope :find_by_domains, ->(domains){includes(:domain_control_validations).where{name>>domains}}
-
scope :validated, ->{joins(:domain_control_validations).where{domain_control_validations.workflow_state=="satisfied"}}
-
scope :last_domain_control_validation, ->{joins(:domain_control_validations).limit(1)}
-
scope :expired_validation, ->{
-
joins(:domain_control_validations)
-
.where('domain_control_validations.id = (SELECT MAX(domain_control_validations.id) FROM domain_control_validations WHERE domain_control_validations.certificate_name_id = certificate_names.id)')
-
.where{(domain_control_validations.responded_at < DomainControlValidation::MAX_DURATION_DAYS[:email].days.ago.to_date)}
-
}
-
scope :unvalidated, ->{
-
satisfied = <<~SQL
-
SELECT COUNT(domain_control_validations.id) FROM domain_control_validations
-
WHERE certificate_name_id = certificate_names.id AND workflow_state='satisfied'
-
SQL
-
total = <<~SQL
-
SELECT COUNT(domain_control_validations.id) FROM domain_control_validations
-
WHERE certificate_name_id = certificate_names.id
-
SQL
-
where "(#{total}) > 0 AND (#{satisfied}) = 0"
-
}
-
scope :sslcom, ->{joins{certificate_content}.where.not certificate_contents: {ca_id: nil}}
-
scope :global, -> {where{(certificate_content_id==nil) & (ssl_account_id==nil) & (acme_account_id==nil)}}
-
scope :search_domains, lambda {|term|
-
term ||= ""
-
term = term.strip.split(/\s(?=(?:[^']|'[^']*')*$)/)
-
filters = { email: nil, name: nil, expired_validation: nil }
-
-
filters.each {|fn, fv|
-
term.delete_if {|str| str =~ Regexp.new(fn.to_s + "\\:\\'?([^']*)\\'?"); filters[fn] ||= $1; $1}
-
}
-
-
term = term.empty? ? nil : term.join(" ")
-
-
return nil if [term, *(filters.values)].compact.empty?
-
-
result = self.all
-
unless term.blank?
-
result = result.where{
-
(email =~ "%#{term}%") |
-
(name =~ "%#{term}%")
-
}
-
end
-
-
%w(expired_validation).each do |field|
-
query = filters[field.to_sym]
-
result = result.expired_validation if query
-
end
-
-
result.uniq.order(created_at: :desc)
-
}
-
-
#will_paginate
-
cattr_accessor :per_page
-
@@per_page = 10
-
-
def is_ip_address?
-
name.index(/\A(?:[0-9]{1,3}\.){3}[0-9]{1,3}\z/)==0 if name
-
end
-
-
def is_server_name?
-
name.index(/\./)==nil if name
-
end
-
-
def is_fqdn?
-
unless is_ip_address? && is_server_name?
-
name.index(/\A[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?\z/ix)==0 if name
-
end
-
end
-
-
def is_intranet?
-
CertificateContent.is_intranet?(name)
-
end
-
-
def is_tld?
-
CertificateContent.is_tld?(name)
-
end
-
-
def top_level_domain
-
if is_fqdn?
-
name=~(/(?:.*?\.)(.+)/)
-
$1
-
end
-
end
-
-
def last_dcv
-
(domain_control_validations.last.try(:dcv_method)=~/https?/) ?
-
domain_control_validations.last : domain_control_validations.last_sent
-
end
-
-
def last_dcv_for_comodo_auto_update_dcv
-
CertificateName.to_comodo_method(domain_control_validations.last.try(:dcv_method))
-
end
-
-
def self.to_comodo_method(dcv_method)
-
case dcv_method
-
when /https/i, ""
-
"HTTPS_CSR_HASH"
-
when /http/i, ""
-
"HTTP_CSR_HASH"
-
when /cname/i
-
"CNAME_CSR_HASH"
-
when /email/i
-
"EMAIL"
-
end
-
end
-
-
def last_dcv_for_comodo
-
case domain_control_validations.last.try(:dcv_method)
-
when /https?/i, ""
-
"HTTPCSRHASH"
-
when /cname/i
-
"CNAMECSRHASH"
-
else
-
domain_control_validations.last_sent.try :email_address
-
end
-
end
-
-
def dcv_url(secure=false, prepend="", check_type=false)
-
"http#{'s' if secure}://#{prepend+non_wildcard_name(check_type)}/.well-known/pki-validation/#{csr.md5_hash}.txt"
-
end
-
-
def cname_origin(check_type=false)
-
"#{csr.dns_md5_hash}.#{non_wildcard_name(check_type)}"
-
end
-
-
def cname_destination
-
csr.cname_destination
-
end
-
-
def non_wildcard_name(check_type=false)
-
check_type && self.certificate_content.certificate_order.certificate.is_single? ?
-
CertificateContent.non_wildcard_name(name,true) :
-
CertificateContent.non_wildcard_name(name,false)
-
end
-
-
# requires csr not be blank
-
def dcv_contents
-
csr.dcv_contents
-
end
-
-
def csr
-
@csr || certificate_content.try(:csr)
-
end
-
-
def cached_csr_public_key_sha1
-
if @csr
-
@csr.public_key_sha1
-
else
-
certificate_content.cached_csr_public_key_sha1
-
end
-
end
-
-
def cached_csr_public_key_md5
-
if @csr
-
@csr.public_key_md5
-
else
-
certificate_content.cached_csr_public_key_md5
-
end
-
end
-
-
def new_name(new_name)
-
@new_name = new_name.downcase if new_name
-
end
-
-
def name
-
ori_name = read_attribute(:name).downcase
-
@new_name ? (@new_name == ori_name ? ori_name : @new_name) : ori_name
-
end
-
-
# if the domain has been validated, do not allow changing it's name
-
def name=(name)
-
dcv=self.domain_control_validations.last
-
super unless (dcv and dcv.satisfied?)
-
end
-
-
def ca_tag
-
csr.ca_tag
-
end
-
-
def dcv_verify(protocol)
-
prepend=""
-
CertificateName.dcv_verify(protocol: protocol,
-
https_dcv_url: dcv_url(true,prepend, true),
-
http_dcv_url: dcv_url(false,prepend, true),
-
cname_origin: cname_origin(true),
-
cname_destination: cname_destination,
-
csr: csr,
-
ca_tag: ca_tag)
-
end
-
-
def self.dcv_verify(options)
-
begin
-
Timeout.timeout(Surl::TIMEOUT_DURATION) do
-
if options[:protocol]=~/https/
-
uri = URI.parse(options[:https_dcv_url])
-
http = Net::HTTP.new(uri.host, uri.port)
-
http.use_ssl = true
-
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
-
request = Net::HTTP::Get.new(uri.request_uri)
-
r = http.request(request).body
-
elsif options[:protocol]=~/cname/
-
txt = Resolv::DNS.open do |dns|
-
records = dns.getresources(options[:cname_origin], Resolv::DNS::Resource::IN::CNAME)
-
end
-
return (txt.size > 0) ? (options[:cname_destination].downcase==txt.last.name.to_s.downcase) : false
-
else
-
r=open(options[:http_dcv_url], "User-Agent" =>
-
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246",
-
redirect: true).read
-
end
-
return true if !!(r =~ Regexp.new("^#{options[:csr].sha2_hash}") &&
-
(options[:ca_tag]=="ssl.com" ? true : r =~ Regexp.new("^#{options[:ca_tag]}")) &&
-
((options[:csr].unique_value.blank? or options[:ignore_unique_value]) ? true : r =~ Regexp.new("^#{options[:csr].unique_value}")))
-
end
-
rescue Exception=>e
-
return false
-
end
-
end
-
-
def whois_lookup
-
if whois_lookups.empty?
-
whois_lookups.create
-
else
-
whois_lookups.last
-
end
-
end
-
-
def update_whois_lookup
-
whois_lookups.create
-
end
-
-
def ca_validation
-
certificate_content.certificate_order.ca_mdc_statuses.last.domain_status[name]
-
end
-
-
def validate_via_cname
-
domain_control_validations.create(dcv_method: "cname").satisfy!
-
end
-
-
def caa_lookup
-
CaaCheck::CAA_COMMAND.call name
-
end
-
-
def get_asynch_cache_label
-
"#{cache_key}/get_asynch_domains/#{non_wildcard_name}"
-
end
-
-
WhoisJob = Struct.new(:dname, :certificate_name) do
-
def perform
-
dcv=DomainControlValidation.global.find_by_subject(dname)
-
if dcv
-
standard_addresses = dcv.candidate_addresses
-
else
-
standard_addresses = DomainControlValidation.email_address_choices(dname)
-
begin
-
d=::PublicSuffix.parse(dname)
-
whois=Whois.whois(ActionDispatch::Http::URL.extract_domain(d.domain, 1)).to_s
-
whois_addresses = WhoisLookup.email_addresses(whois)
-
whois_addresses.each do |ad|
-
standard_addresses << ad.downcase unless ad =~/abuse.*?@/i
-
end unless whois_addresses.blank?
-
rescue Exception=>e
-
Logger.new(STDOUT).error e.backtrace.inspect
-
end
-
DomainControlValidation.global.find_or_create_by(subject: dname).update_column(:candidate_addresses,
-
standard_addresses)
-
end
-
Rails.cache.write("CertificateName.candidate_email_addresses/#{dname}",standard_addresses,
-
expires_in: DomainControlValidation::EMAIL_CHOICE_CACHE_EXPIRES_DAYS.days)
-
cert_names=CertificateName.where("name = ?", "#{dname}")
-
cert_names.update_all(updated_at: Time.now)
-
cert_names.each{|cn| Rails.cache.delete(cn.get_asynch_cache_label)}
-
CertificateContent.where{id >> cert_names.map(&:certificate_content_id)}.update_all(updated_at: Time.now)
-
if certificate_name
-
dcv=certificate_name.domain_control_validations.last
-
dcv.update_column(:candidate_addresses, standard_addresses) if dcv
-
end
-
end
-
-
def max_attempts
-
3
-
end
-
-
def max_run_time
-
300 # seconds
-
end
-
end
-
-
def candidate_email_addresses(clear_cache=false)
-
Rails.cache.delete("CertificateName.candidate_email_addresses/#{non_wildcard_name}") if clear_cache
-
CertificateName.candidate_email_addresses(name,self)
-
end
-
-
# certificate_name in the event the domain_control_validations candidate addresses need to be updated
-
def self.candidate_email_addresses(name,certificate_name=nil)
-
name=CertificateContent.non_wildcard_name(name,false)
-
Rails.cache.fetch("CertificateName.candidate_email_addresses/#{name}",
-
expires_in: DomainControlValidation::EMAIL_CHOICE_CACHE_EXPIRES_DAYS.days) do
-
Delayed::Job.enqueue WhoisJob.new(name,certificate_name) unless APP_URL=~Regexp.new(Settings.portal_domain)
-
DomainControlValidation.global.find_by_subject(name).try(:candidate_addresses) ||
-
DomainControlValidation.email_address_choices(name)
-
end
-
end
-
-
def self.add_email_address_candidate(dname,email_address)
-
Rails.cache.delete("CertificateName.candidate_email_addresses/#{dname}")
-
cert_names=CertificateName.where("name = ?", "#{dname}")
-
cert_names.update_all(updated_at: Time.now)
-
cert_names.each{|cn| Rails.cache.delete(cn.get_asynch_cache_label)}
-
CertificateContent.where{id >> cert_names.map(&:certificate_content_id)}.update_all(updated_at: Time.now)
-
standard_addresses=CertificateName.candidate_email_addresses(dname)
-
standard_addresses << email_address
-
DomainControlValidation.global.find_or_create_by(subject: dname).update_column(
-
:candidate_addresses, standard_addresses)
-
end
-
end
-
1
class CertificateOrder < ActiveRecord::Base
-
1
extend Memoist
-
1
include V2MigrationProgressAddon
-
#using_access_control
-
1
acts_as_sellable :cents => :amount, :currency => false
-
1
belongs_to :ssl_account, touch: true
-
1
belongs_to :folder, touch: true
-
1
has_many :users, through: :ssl_account
-
1
belongs_to :assignee, class_name: "User"
-
1
belongs_to :validation
-
1
has_many :validation_histories, through: :validation
-
1
belongs_to :site_seal
-
1
belongs_to :parent, class_name: 'CertificateOrder', :foreign_key=>:renewal_id
-
1
has_one :renewal, class_name: 'CertificateOrder', :foreign_key=>:renewal_id,
-
:dependent=>:destroy #represents a child renewal
-
1
has_many :renewal_attempts
-
1
has_many :renewal_notifications
-
1
has_many :cdns
-
1
has_many :certificate_contents, :dependent => :destroy, after_add: Proc.new { |p, d| p.certificate_content(true)}
-
1
has_many :certificate_names, through: :certificate_contents
-
1
has_one :locked_recipient, class_name: 'LockedRecipient',
-
as: :contactable, dependent: :destroy
-
1
has_many :registrants, through: :certificate_contents
-
1
has_many :locked_registrants, through: :certificate_contents
-
1
has_many :certificate_contacts, through: :certificate_contents
-
1
has_many :domain_control_validations, through: :certificate_names
-
1
has_many :csrs, :through=>:certificate_contents, :source=>"csr"
-
1
has_many :csr_unique_values, through: :csrs
-
1
has_many :signed_certificates, :through=>:csrs do
-
1
def expired
-
where{expiration_date < Date.today}
-
end
-
end
-
1
has_many :shadow_certificates, :through=>:csrs, class_name: "ShadowSignedCertificate"
-
1
has_many :ca_certificate_requests, :through=>:csrs
-
1
has_many :ca_api_requests, :through=>:csrs
-
1
has_many :sslcom_ca_requests, :through=>:csrs
-
1
has_many :sub_order_items, :as => :sub_itemable, :dependent => :destroy
-
1
has_many :product_variant_items, through: :sub_order_items, :dependent => :destroy
-
1
has_many :orders, :through => :line_items, unscoped: true
-
1
has_many :other_party_validation_requests, class_name: "OtherPartyValidationRequest",
-
as: :other_party_requestable, dependent: :destroy
-
1
has_many :ca_retrieve_certificates, as: :api_requestable, dependent: :destroy
-
1
has_many :ca_mdc_statuses, as: :api_requestable
-
#has_many :client_order_certificate_requests, class_name: "ClientOrderCertificateRequest",
-
# as: :api_requestable, dependent: :destroy
-
1
has_many :jois, as: :contactable, class_name: 'Joi' # for SSL.com EV; rw by vetting agents, r by customer
-
1
has_many :app_reps, as: :contactable, class_name: 'AppRep' # for SSL.com OV and EV; rw by vetting agents, r by customer
-
1
has_many :physical_tokens
-
1
has_many :url_callbacks, as: :callbackable, :through=>:certificate_contents
-
1
has_many :taggings, as: :taggable
-
1
has_many :tags, through: :taggings
-
1
has_many :notification_groups_subjects, as: :subjectable
-
1
has_many :notification_groups, through: :notification_groups_subjects
-
1
has_many :certificate_order_tokens
-
1
has_many :certificate_order_managed_csrs, dependent: :destroy
-
1
has_many :managed_csrs, through: :certificate_order_managed_csrs
-
1
has_many :certificate_order_domains, dependent: :destroy
-
1
has_many :managed_domains, through: :certificate_order_domains, :source => :domain
-
-
1
accepts_nested_attributes_for :certificate_contents, :allow_destroy => false
-
1
attr_accessor :duration, :has_csr
-
-
# the following only apply to api calls
-
1
attr_accessor :certificate_url, :receipt_url, :smart_seal_url, :validation_url, :dcv_method,
-
:dcv_email_address, :dcv_candidate_addresses
-
-
#will_paginate
-
1
cattr_accessor :per_page
-
1
@@per_page = 10
-
-
#used to temporarily determine lineitem qty
-
1
attr_accessor :quantity
-
1
preference :payment_order, :string, :default=>"normal"
-
1
preference :certificate_chain, :string
-
-
#if the customer has not used this certificate order with a period of time
-
#it becomes expired and invalid
-
1
alias_attribute :expired, :is_expired
-
-
1
if Proc.new{|co|co.migrated_from_v2?}
-
1
preference :v2_product_description, :string, :default=>'ssl certificate'
-
1
preference :v2_line_items, :string
-
end
-
-
1
default_scope{ where{(workflow_state << ['canceled','refunded','charged_back']) & (is_expired != true)}.
-
order(created_at: :desc)}
-
-
1
scope :with_counts, -> {
-
select <<~SQL
-
certificate_orders.*,
-
(
-
SELECT COUNT(certificate_contents.id) FROM certificate_contents
-
WHERE certificate_order_id = certificate_orders.id
-
) AS certificate_contents_count
-
SQL
-
}
-
-
1
scope :not_test, ->{where{(is_test == nil) | (is_test==false)}}
-
-
1
scope :is_test, ->{where{is_test==true}}
-
-
1
scope :search, lambda {|term, options={}|
-
where{ref =~ '%'+term+'%'}.merge(options)
-
}
-
-
1
scope :search_physical_tokens, lambda {|state="new"|
-
joins{physical_tokens}.where{physical_tokens.workflow_state >> [state.split(',')]} unless state.blank?
-
}
-
-
1
scope :search_signed_certificates, lambda {|term|
-
joins{certificate_contents.csr.signed_certificates}.
-
where{certificate_contents.csr.signed_certificates.common_name =~ "%#{term}%"}
-
}
-
-
1
scope :search_csr, lambda {|term|
-
joins{certificate_contents.csr}.where{certificate_contents.csr.common_name =~ "%#{term}%"}
-
}
-
-
1
scope :search_assigned, lambda { |term|
-
joins{ assignee }.where{ assignee.id == term }
-
}
-
-
1
scope :search_validated_not_assigned, lambda { |term|
-
2
joins{ certificate_contents }.
-
1
joins{ certificate_contents.locked_registrant }.
-
1
where{ (assignee_id == nil ) &
-
1
(certificate_contents.workflow_state == 'validated') &
-
1
(certificate_contents.locked_registrant.email == term)
-
}
-
}
-
-
1
scope :search_with_csr, lambda {|term, options={}|
-
term ||= ""
-
term = term.strip.split(/\s(?=(?:[^']|'[^']*')*$)/)
-
filters = {common_name: nil, organization: nil, organization_unit: nil, address: nil, state: nil, postal_code: nil,
-
subject_alternative_names: nil, locality: nil, country:nil, signature: nil, fingerprint: nil, strength: nil,
-
expires_at: nil, created_at: nil, login: nil, email: nil, account_number: nil, product: nil,
-
decoded: nil, is_test: nil, order_by_csr: nil, physical_tokens: nil, issued_at: nil, notes: nil,
-
ref: nil, external_order_number: nil, status: nil, duration: nil, co_tags: nil, cc_tags: nil,
-
folder_ids: nil}
-
filters.each{|fn, fv|
-
term.delete_if {|s|s =~ Regexp.new(fn.to_s+"\\:\\'?([^']*)\\'?"); filters[fn] ||= $1; $1}
-
}
-
term = term.empty? ? nil : term.join(" ")
-
return nil if [term,*(filters.values)].compact.empty?
-
result = not_new
-
cc_query=CertificateContent
-
keys=filters.map{|f|f[0] if !f[1].blank?}.compact
-
unless term.blank?
-
# if 'is_test' and 'order_by_csr' are the only search terms, keep it simple
-
sql=%(MATCH (csrs.common_name, csrs.body, csrs.decoded) AGAINST ('#{term}') OR
-
MATCH (signed_certificates.common_name, signed_certificates.url, signed_certificates.body,
-
signed_certificates.decoded, signed_certificates.ext_customer_ref, signed_certificates.ejbca_username)
-
AGAINST ('#{term}') OR
-
MATCH (ssl_accounts.acct_number, ssl_accounts.company_name, ssl_accounts.ssl_slug) AGAINST ('#{term}') OR
-
MATCH (certificate_orders.ref, certificate_orders.external_order_number, certificate_orders.notes) AGAINST ('#{term}') OR
-
MATCH (users.login, users.email) AGAINST ('#{term}')).squish
-
result = result.joins{csrs}.joins{csrs.signed_certificates.outer}.joins{ssl_account.outer}.
-
joins{ssl_account.users.outer}.where(sql)
-
end
-
result=result.joins{ssl_account.outer} unless (keys & [:account_number]).empty?
-
result=result.joins{ssl_account.users.outer} unless (keys & [:login, :email]).empty?
-
cc_query=(cc_query || CertificateContent).joins{csrs} unless
-
(keys & [:country, :strength, :common_name, :organization, :organization_unit, :state,
-
:subject_alternative_names, :locality, :decoded]).empty?
-
cc_query=(cc_query || CertificateContent).joins{csr.signed_certificates.outer} unless
-
(keys & [:country, :strength, :postal_code, :signature, :fingerprint, :expires_at, :created_at, :issued_at,
-
:common_name, :organization, :organization_unit, :state, :subject_alternative_names, :locality,
-
:decoded, :address]).empty?
-
%w(is_test).each do |field|
-
query=filters[field.to_sym]
-
if query.try("true?")
-
result = result.send(field)
-
elsif query.try("false?")
-
result = result.not_test
-
end
-
end
-
%w(order_by_csr).each do |field|
-
query=filters[field.to_sym]
-
result = result.send(field) if query.try("true?")
-
end
-
%w(physical_tokens).each do |field|
-
query=filters[field.to_sym]
-
result = result.search_physical_tokens(query) if query
-
end
-
%w(postal_code signature fingerprint).each do |field|
-
query=filters[field.to_sym]
-
cc_query = cc_query.where{
-
(csr.signed_certificates.send(field.to_sym) =~ "%#{query}%")} if query
-
end
-
%w(product).each do |field|
-
query=filters[field.to_sym]
-
result = result.filter_by(query) if query
-
end
-
%w(duration).each do |field|
-
query=filters[field.to_sym]
-
result = result.filter_by_duration(query) if query
-
end
-
%w(ref).each do |field|
-
query=filters[field.to_sym]
-
if query
-
result = result.where{ref >> query.split(',')}
-
cc_query = cc_query.where{ref >> query.split(',')}
-
end
-
end
-
%w(country strength).each do |field|
-
query=filters[field.to_sym]
-
cc_query = cc_query.where{
-
(csr.signed_certificates.send(field.to_sym) >> query.split(',')) |
-
(csrs.send(field.to_sym) >> query.split(','))} if query
-
end
-
%w(status).each do |field|
-
query=filters[field.to_sym]
-
if query
-
cc_query = cc_query.where{workflow_state >> query.split(',')}
-
end
-
end
-
%w(common_name organization organization_unit state subject_alternative_names locality decoded).each do |field|
-
query=filters[field.to_sym]
-
cc_query = cc_query.where{
-
(csr.signed_certificates.send(field.to_sym) =~ "%#{query}%") |
-
(csrs.send(field.to_sym) =~ "%#{query}%") } if query
-
end
-
%w(address).each do |field|
-
query=filters[field.to_sym]
-
cc_query = cc_query.where{
-
(csr.signed_certificates.address1 =~ "%#{query}%") |
-
(csr.signed_certificates.address2 =~ "%#{query}%")} if query
-
end
-
%w(login email).each do |field|
-
query=filters[field.to_sym]
-
result = result.where{
-
(ssl_account.users.send(field.to_sym) =~ "%#{query}%")} if query
-
end
-
%w(account_number).each do |field|
-
query=filters[field.to_sym]
-
result = result.where{
-
(ssl_account.send(field.to_sym) =~ "%#{query}%")} if query
-
end
-
%w(expires_at created_at issued_at).each do |field|
-
query=filters[field.to_sym]
-
if query
-
query=query.split("-")
-
start = Date.strptime query[0], "%m/%d/%Y"
-
finish = query[1] ? Date.strptime(query[1], "%m/%d/%Y") : start+1.day
-
if(field=="expires_at")
-
cc_query = cc_query.where{(csr.signed_certificates.expiration_date >> (start..finish))}
-
elsif(field=="issued_at")
-
cc_query = cc_query.where{(csr.signed_certificates.created_at >> (start..finish))}
-
else
-
result = result.where{created_at >> (start..finish)}
-
end
-
end
-
end
-
%w(co_tags).each do |field|
-
query = filters[field.to_sym]
-
if query
-
@result_prior_co_tags = result
-
result = result.joins(:tags).where(tags: {name: query.split(',')})
-
end
-
end
-
%w(cc_tags).each do |field|
-
query = filters[field.to_sym]
-
if query
-
cc_results = (@result_prior_co_tags || result)
-
.joins(certificate_contents: [:tags]).where(tags: {name: query.split(',')})
-
-
result = if @result_prior_co_tags.nil?
-
cc_results
-
else
-
# includes tags in BOTH certificate orders and certificate contents tags, not a union
-
CertificateOrder.where(id: (result + cc_results).map(&:id).uniq)
-
end
-
end
-
end
-
%w(folder_ids).each do |field|
-
query = filters[field.to_sym]
-
result = result.where(folder_id: query.split(',')) if query
-
end
-
if cc_query!=CertificateContent
-
ids=cc_query.pluck(:id).uniq
-
unless ids.empty?
-
result.joins{certificate_contents}.where{certificate_contents.id >> ids}
-
else
-
result.uniq
-
end
-
else
-
result.uniq
-
end
-
}
-
-
# scope :reprocessing, lambda {
-
# cids=Preference.select("owner_id").joins{owner(CertificateContent)}.
-
# where{(name=="reprocessing") & (value==1)}.map(&:owner_id)
-
# joins{certificate_contents.csr}.where{certificate_contents.id >> cids}.order("csrs.updated_at asc")
-
# }
-
-
# more elegant but needs to be refined. Too slow
-
# scope :reprocessing1, lambda {
-
# cids=Preference.joins{owner(CertificateContent)}.
-
# where{(name=="reprocessing") & (value==1)}.select{owner_id}
-
# joins{certificate_contents.csr}.where{certificate_contents.id.in(cids)}.order("csrs.updated_at asc")
-
# }
-
#
-
1
scope :order_by_csr, lambda {
-
joins{certificate_contents.csr.outer}.order("csrs.created_at desc") #.uniq #- breaks order by csr
-
}
-
-
1
scope :filter_by, lambda { |term|
-
terms = term.split(',').map{|t|t+'%'}
-
joins{sub_order_items.product_variant_item.product_variant_group.
-
variantable(Certificate)}.where(('certificates.product like ?@' * terms.count).split('@').join(' OR '), *terms)
-
}
-
-
1
scope :filter_by_duration, lambda { |term|
-
joins{certificate_contents}.where{certificate_contents.duration >> term.split(',')}
-
}
-
-
1
scope :unvalidated, ->{joins(:certificate_contents).where{(is_expired==false) &
-
(certificate_contents.workflow_state >> ['pending_validation', 'contacts_provided'])}.
-
order("certificate_contents.updated_at asc")}
-
-
1
scope :not_csr_blank, ->{joins{certificate_contents.csr}.where{certificate_contents.csr.id!=nil}}
-
-
1
scope :incomplete, ->{not_test.joins(:certificate_contents).where{(is_expired==false) &
-
(certificate_contents.workflow_state >> ['csr_submitted', 'info_provided', 'contacts_provided'])}.
-
order("certificate_contents.updated_at asc")}
-
-
1
scope :pending, ->{not_test.joins(:certificate_contents).where{certificate_contents.workflow_state >>
-
['pending_validation', 'validated']}.order("certificate_contents.updated_at asc")}
-
-
1
scope :has_csr, ->{not_test.joins(:certificate_contents).where{(workflow_state=='paid') &
-
(certificate_contents.signing_request != "")}.order("certificate_contents.updated_at asc")}
-
-
1
scope :credits, ->{not_test.joins(:certificate_contents).where({:workflow_state=>'paid'} & {is_expired: false} &
-
{:certificate_contents=>{workflow_state: "new"}})} # and not new
-
-
#new certificate orders are the ones still in the shopping cart
-
1
scope :not_new, lambda {|options=nil|
-
if options && options.has_key?(:includes)
-
includes=method(:includes).call(options[:includes])
-
end
-
(includes || self).where{workflow_state << ['new']}.uniq
-
}
-
-
1
scope :is_new, lambda {where{workflow_state >> ['new']}.uniq}
-
-
1
scope :unrenewed, ->{not_new.where(:renewal_id=>nil)}
-
-
1
scope :renewed, ->{not_new.where{:renewal_id != nil}}
-
-
1
scope :nonfree, ->{not_new.where(:amount.gt => 0)}
-
-
1
scope :free, ->{not_new.where(:amount => 0)}
-
-
1
scope :unused_credits, ->{
-
unused = joins{}
-
where{(workflow_state=='paid') & (is_expired==false) & (id << unused.joins{certificate_contents.csr.signed_certificates.outer}.pluck(id).uniq)}
-
}
-
-
1
scope :used_credits, ->{
-
unused = where{(workflow_state=='paid') & (is_expired==false)}
-
where{id >> unused.joins{certificate_contents.csr.signed_certificates.outer}.pluck(id)}
-
}
-
-
1
scope :unflagged_expired_credits, ->{unused_credits.
-
where{created_at < Settings.cert_expiration_threshold_days.to_i.days.ago}}
-
-
1
scope :unused_purchased_credits, ->{unused_credits.where{amount > 0}}
-
-
1
scope :unused_free_credits, ->{unused_credits.where{amount == 0}}
-
-
1
scope :falsely_expired, -> {unscoped.where{(workflow_state=='paid') & (is_expired==true) &
-
(external_order_number != nil)}}
-
-
1
scope :range, lambda{|start, finish|
-
if start.is_a?(String)
-
(s= start =~ /\// ? "%m/%d/%Y" : "%m-%d-%Y")
-
start = Date.strptime(start, s)
-
end
-
if finish.is_a?(String)
-
(f= finish =~ /\// ? "%m/%d/%Y" : "%m-%d-%Y")
-
finish = Date.strptime(finish, f)
-
end
-
where{created_at >> (start..finish)}
-
} do
-
-
1
def amount
-
self.nonfree.sum(:amount)*0.01
-
end
-
end
-
-
1
FULL = 'full'
-
1
EXPRESS = 'express'
-
1
PREPAID_FULL = 'prepaid_full'
-
1
PREPAID_EXPRESS = 'prepaid_express'
-
1
VERIFICATION_STEP = 'Perform Validation'
-
1
CLIENT_SMIME_VALIDATE = 'client_smime_validate'
-
1
CLIENT_SMIME_VALIDATED = 'client_smime_validated'
-
1
CLIENT_SMIME_VALIDATED_SHORT = 'client_smime_validated_short'
-
-
1
FULL_SIGNUP_PROCESS = {:label=>FULL, :pages=>%W(Submit\ CSR Payment
-
Registrant Contacts #{VERIFICATION_STEP} Complete)}
-
1
EXPRESS_SIGNUP_PROCESS = {:label=>EXPRESS,
-
:pages=>FULL_SIGNUP_PROCESS[:pages] - %w(Contacts)}
-
1
PREPAID_FULL_SIGNUP_PROCESS = {:label=>PREPAID_FULL,
-
:pages=>FULL_SIGNUP_PROCESS[:pages] - %w(Payment)}
-
1
NO_CSR_SIGNUP_PROCESS = {:label=>PREPAID_FULL,
-
:pages=>PREPAID_FULL_SIGNUP_PROCESS[:pages] - %w(Submit\ CSR)}
-
1
PREPAID_EXPRESS_SIGNUP_PROCESS = {:label=>PREPAID_EXPRESS,
-
:pages=>EXPRESS_SIGNUP_PROCESS[:pages] - %w(Payment)}
-
1
REPROCES_SIGNUP_W_PAYMENT = {label: FULL,
-
pages: FULL_SIGNUP_PROCESS[:pages]}
-
1
REPROCES_SIGNUP_W_INVOICE = {label: PREPAID_EXPRESS,
-
pages: FULL_SIGNUP_PROCESS[:pages] - %w(Payment)}
-
CLIENT_SMIME_FULL = {
-
1
label: CLIENT_SMIME_VALIDATE,
-
pages: ['Registrant', 'Recipient', 'Upload Documents', 'Complete']
-
}
-
CLIENT_SMIME_IV_VALIDATE = {
-
1
label: CLIENT_SMIME_VALIDATE,
-
pages: ['Recipient', 'Upload Documents', 'Complete']
-
}
-
CLIENT_SMIME_IV_VALIDATED = {
-
1
label: CLIENT_SMIME_VALIDATE,
-
pages: ['Recipient', 'Complete']
-
}
-
CLIENT_SMIME_NO_DOCS = {
-
1
label: CLIENT_SMIME_VALIDATED,
-
pages: ['Registrant', 'Recipient', 'Complete']
-
}
-
CLIENT_SMIME_NO_IV_OV = {
-
1
label: CLIENT_SMIME_VALIDATED_SHORT,
-
pages: ['Recipient', 'Complete']
-
}
-
-
1
CSR_SUBMITTED = :csr_submitted
-
1
INFO_PROVIDED = :info_provided
-
1
REPROCESS_REQUESTED = :reprocess_requested
-
1
CONTACTS_PROVIDED = :contacts_provided
-
-
1
CA_CERTIFICATES = {SSLcomSHA2: "SSLcomSHA2"}
-
-
1
STATUS = {CSR_SUBMITTED=>'info required',
-
INFO_PROVIDED=> 'contacts required',
-
REPROCESS_REQUESTED => 'csr required',
-
CONTACTS_PROVIDED => 'validation required'}
-
-
1
RENEWING = 'renewing'
-
1
REPROCESSING = 'reprocessing'
-
1
RECERTS = [RENEWING, REPROCESSING]
-
1
RENEWAL_DATE_CUTOFF = 45.days.ago
-
1
RENEWAL_DATE_RANGE = 45.days.from_now
-
1
ID_AND_TIMESTAMP=["id", "created_at", "updated_at"]
-
1
COMODO_SSL_MAX_DURATION = 730
-
1
SSL_MAX_DURATION = 820
-
1
EV_SSL_MAX_DURATION = 730
-
1
CS_MAX_DURATION = 1095
-
1
CLIENT_MAX_DURATION = 1095
-
1
SMIME_MAX_DURATION = 1095
-
1
TS_MAX_DURATION = 4106
-
-
# changed for the migration
-
# unless MIGRATING_FROM_LEGACY
-
# validates :certificate, presence: true
-
# else
-
# validates :certificate, presence: true, :unless=>Proc.new {|co|
-
# !co.orders.last.nil? && (co.orders.last.preferred_migrated_from_v2 == true)}
-
# end
-
-
1
before_create do |co|
-
default_folder = Folder.find_by(default: true, ssl_account_id: ssl_account_id)
-
co.folder_id = default_folder.id if default_folder
-
co.ca = CA_CERTIFICATES[:SSLcomSHA2]
-
co.is_expired=false
-
co.ref='co-'+SecureRandom.hex(1)+Time.now.to_i.to_s(32)
-
v =co.create_validation
-
co.preferred_certificate_chain = co.certificate.preferred_certificate_chain
-
co.certificate.validation_rulings.each do |cvrl|
-
vrl = cvrl.dup
-
vrl.status = ValidationRuling::WAITING_FOR_DOCS
-
vrl.workflow_state = "new"
-
v.validation_rulings << vrl
-
end
-
co.site_seal=SiteSeal.create
-
end
-
-
1
after_initialize do
-
if new_record?
-
self.quantity ||= 1
-
self.has_csr ||= false
-
end
-
end
-
-
1
include Workflow
-
1
workflow do
-
1
state :new do
-
1
event :pay, :transitions_to => :paid do |payment|
-
halt unless payment
-
post_process_csr unless is_prepaid?
-
end
-
1
event :reject, :transitions_to => :rejected
-
1
event :cancel, :transitions_to => :canceled
-
end
-
-
1
state :paid do
-
1
event :cancel, :transitions_to => :canceled
-
1
event :reject, :transitions_to => :rejected
-
1
event :refund, :transitions_to => :refunded
-
1
event :charge_back, :transitions_to => :charged_back
-
1
event :start_over, transitions_to: :paid do |complete=false|
-
if self.certificate_contents.count >1
-
cc = self.certificate_contents.last
-
cc.preserve_certificate_contacts
-
cc.delete
-
else
-
duration = self.certificate_content.duration
-
temp_cc=self.certificate_contents.create(duration: duration)
-
# Do not delete the last one
-
(self.certificate_contents-[temp_cc]).each do |cc|
-
cc.delete if ((cc.csr or cc.csr.try(:signed_certificate)) || complete)
-
end
-
end
-
end
-
end
-
-
1
state :canceled do
-
1
event :uncancel, :transitions_to => :paid
-
1
event :unrefund, :transitions_to => :canceled
-
1
event :refund, :transitions_to => :refunded
-
1
event :reject, :transitions_to => :rejected
-
1
event :charge_back, :transitions_to => :charged_back
-
1
event :cancel, :transitions_to => :canceled
-
end
-
-
1
state :refunded do #only refund a canceled order
-
1
event :unrefund, :transitions_to => :paid
-
1
event :reject, :transitions_to => :rejected
-
1
event :charge_back, :transitions_to => :charged_back
-
end
-
-
1
state :charged_back
-
-
1
state :rejected do #only refund a canceled order
-
1
event :cancel, :transitions_to => :canceled
-
1
event :unreject, :transitions_to => :paid
-
1
event :refund, :transitions_to => :refunded
-
end
-
end
-
-
1
def locked_recipient_subject_dn
-
dn = []
-
if get_recipient
-
dn << "CN=#{[locked_recipient.first_name,locked_recipient.last_name].join(" ").strip}"
-
dn << "emailAddress=#{locked_recipient.email}"
-
-
dn.map{|d|d.gsub(/\\/,'\\\\').gsub(',','\,')}.join(",")
-
end
-
end
-
-
1
def get_recipient
-
recipient = locked_recipient
-
if locked_recipient.nil? && assignee
-
recipient = LockedRecipient.create_for_co(self)
-
end
-
recipient
-
end
-
-
1
def get_audit_logs
-
SystemAudit.where(
-
"(target_id = ? AND target_type = ?) OR (target_id IN (?) AND target_type = ?)",
-
id, 'CertificateOrder', line_items.ids, 'LineItem'
-
).order('created_at desc')
-
end
-
-
-
1
def domains_adjust_billing?
-
certificate.is_ucc? && (certificate.is_premium_ssl? !=0) &&
-
orders.count > 0 && orders.first.persisted?
-
end
-
-
# Prorated pricing for single domain for ucc certificate,
-
# used in calculating reprocessing amount for additional domains.
-
1
def ucc_prorated_domain(type, reseller_tier=nil)
-
if certificate.is_ucc?
-
tiers = ucc_duration_amounts(certificate_duration(:years).to_i, reseller_tier)
-
domain_amount = (type == :wildcard && !certificate.is_ev?) ? tiers['tier_3'] : tiers['tier_2']
-
total_duration = certificate_duration(:days)
-
domain_amount - ( (used_days/total_duration) * domain_amount )
-
end
-
end
-
-
# Get pricing for each tier for a given duration,
-
# used in calculating reprocessing amount for additional domains.
-
1
def ucc_duration_amounts(years=1, reseller_tier=nil)
-
if certificate.is_ucc?
-
durations = {}
-
i = years-1
-
cur_certificate = certificate
-
-
unless reseller_tier.blank?
-
ssl_tier = ssl_account.reseller_tier_label
-
unless ssl_tier.blank?
-
reseller_tier = reseller_tier.include?(ssl_tier) ? reseller_tier : "#{ssl_tier}tr"
-
end
-
cur_certificate = Certificate.tiered_products(/\-?#{reseller_tier}/)
-
.find {|c| c.title == certificate.title}
-
cur_certificate = certificate if cur_certificate.nil?
-
end
-
-
cur_certificate.num_domain_tiers.times do |j|
-
durations["tier_#{j+1}"] = (cur_certificate.items_by_domains(true)[i][j].price * ( (j==0) ? 3 : 1 )).cents
-
end
-
durations
-
end
-
end
-
-
1
def ucc_get_max_counts(certificate_content=nil)
-
max_wildcard_count = get_reprocess_max_wildcard(certificate_content).count
-
max_nonwildcard_count = get_reprocess_max_nonwildcard(certificate_content).count
-
-
# check against counts of certificate's initial purchase
-
if !wildcard_count.blank? && (wildcard_count > max_wildcard_count)
-
max_wildcard_count = wildcard_count
-
end
-
if !nonwildcard_count.blank? && (nonwildcard_count > max_nonwildcard_count)
-
max_nonwildcard_count = nonwildcard_count
-
end
-
-
{wildcard_count: max_wildcard_count, nonwildcard_count: max_nonwildcard_count}
-
end
-
-
1
def ucc_prorated_amount(certificate_content, reseller_tier=nil)
-
max = ucc_get_max_counts(certificate_content)
-
max_wildcard_count = max[:wildcard_count]
-
max_nonwildcard_count = max[:nonwildcard_count]
-
-
# make sure NOT to charge for tier 1 domains (3 total)
-
max_nonwildcard_count = (max_nonwildcard_count < 3) ? 3 : max_nonwildcard_count
-
nonwildcard_cost = ucc_prorated_domain(:nonwildcard, reseller_tier)
-
wildcard_cost = ucc_prorated_domain(:wildcard, reseller_tier)
-
new_nonwildcard_count = 0
-
new_wildcard_count = 0
-
certificate_content.domains.each do |name|
-
name.include?('*') ? (new_wildcard_count +=1) : (new_nonwildcard_count +=1)
-
end
-
addt_nonwildcard = new_nonwildcard_count - max_nonwildcard_count
-
addt_wildcard = new_wildcard_count - max_wildcard_count
-
addt_nonwildcard = (addt_nonwildcard < 0) ? 0 : addt_nonwildcard
-
addt_wildcard = (addt_wildcard < 0) ? 0 : addt_wildcard
-
(addt_nonwildcard * nonwildcard_cost) + (addt_wildcard * wildcard_cost)
-
end
-
-
# Retrieve certificate contents signed certificate (subject_alternative_names).
-
# IF certificate content is passed, THEN consider ONLY certificate
-
# contents prior to passed certificate content.
-
1
def get_reprocess_cc_domains(cc_id=nil)
-
cur_domains = []
-
if certificate_contents.any?
-
cur_domains = certificate_contents.includes(:signed_certificates).where(workflow_state: 'issued')
-
end_target = certificate_contents.find_by(id: cc_id) unless cc_id.nil?
-
if end_target
-
cur_domains = cur_domains.where(
-
created_at: certificate_contents.first.created_at...end_target.created_at
-
)
-
end
-
end
-
if cur_domains.any?
-
cur_domains = cur_domains.map(&:signed_certificates).compact
-
.reject{ |sc| sc.empty? }.flatten.map(&:subject_alternative_names)
-
end
-
-
if cur_domains.empty? && (renew_billing? || domains_adjust_billing?)
-
cur_domains = certificate_contents.map(&:domains)
-
end
-
cur_domains
-
end
-
1
memoize :get_reprocess_cc_domains
-
-
1
def get_reprocess_max_nonwildcard(cc_id=nil)
-
max = 0
-
list = []
-
get_reprocess_cc_domains(cc_id).each do |arr|
-
cur_max = arr.map {|d| d if !d.include?('*')}.compact
-
if cur_max.count > max
-
max = cur_max.count
-
list = cur_max
-
end
-
end
-
list
-
end
-
-
1
def get_reprocess_max_wildcard(cc_id=nil)
-
max = 0
-
list = []
-
get_reprocess_cc_domains(cc_id).each do |arr|
-
cur_max = arr.map {|d| d if d.include?('*')}.compact
-
if cur_max.count > max
-
max = cur_max.count
-
list = cur_max
-
end
-
end
-
list
-
end
-
-
1
def add_reproces_order(target_order)
-
target_order.save unless target_order.persisted?
-
target_order.line_items.destroy_all
-
if target_order.valid?
-
line_items.create(
-
order_id: target_order.id, cents: target_order.cents, amount: target_order.amount, currency: 'USD'
-
)
-
end
-
# clear cache
-
target_order.touch
-
self.touch
-
end
-
-
1
def certificate
-
if new_record?
-
sub_order_items[0].product_variant_item.certificate if sub_order_items[0] &&
-
sub_order_items[0].product_variant_item
-
else
-
Certificate.unscoped.find_by_id(Rails.cache.fetch("#{cache_key}/certificate") do
-
sub_order_items[0].product_variant_item.cached_certificate_id if sub_order_items[0] &&
-
sub_order_items[0].product_variant_item
-
end)
-
end
-
end
-
1
memoize :certificate
-
-
1
def signed_certificate
-
signed_certificates.order(:created_at).last
-
end
-
-
1
def comodo_ca_id
-
(signed_certificate || certificate).comodo_ca_id
-
end
-
-
# find the ratio remaining on the cert ie (today-effective_date/expiration_date-effective_date)
-
1
def duration_remaining(options={duration: :order})
-
remaining_days(options)/total_days(options)
-
end
-
-
1
def used_days(options={round: false})
-
if signed_certificates && !signed_certificates.empty?
-
sum = (Time.now - (signed_certificates.sort{|a,b|a.created_at.to_i<=>b.created_at.to_i}.first.effective_date ||
-
self.created_at))
-
(options[:round] ? sum.round : sum)/1.day
-
else
-
0
-
end
-
end
-
-
1
def remaining_days(options={round: false, duration: :order})
-
tot, used = total_days(options), used_days(options)
-
if tot && used && tot>used
-
days = total_days(options)-used_days(options)
-
(options[:round] ? days.round : days)
-
else
-
0
-
end
-
end
-
-
1
def signed_certificate_duration_delta
-
remaining_days - remaining_days(duration: :actual)
-
end
-
-
1
def unchain_comodo
-
update_column(:external_order_number, nil) unless external_order_number.blank?
-
if certificate_content.ca_id.blank?
-
certificate_content.add_ca(ssl_account)
-
certificate_content.save
-
end
-
end
-
-
# :actual is based on the duration of the signed cert, :order is the duration based on the certificate order
-
1
def total_days(options={round: false, duration: :order})
-
if options[:duration]== :actual
-
if signed_certificates && !signed_certificates.empty?
-
sum = (signed_certificates.sort{|a,b|a.created_at.to_i<=>b.created_at.to_i}.last.expiration_date -
-
signed_certificates.sort{|a,b|a.created_at.to_i<=>b.created_at.to_i}.first.effective_date)
-
(options[:round] ? sum.round : sum)/1.day
-
else
-
0
-
end
-
else
-
certificate_duration(:days)
-
end
-
end
-
-
# unit can be :days or :years
-
1
def certificate_duration(unit=:as_is)
-
Rails.cache.fetch("#{cache_key}/certificate_duration/#{unit.to_s}", expires_in: 24.hours) do
-
years=if migrated_from_v2? && !preferred_v2_line_items.blank?
-
preferred_v2_line_items.split('|').detect{|item|
-
item =~/years?/i || item =~/days?/i}.scan(/\d+.+?(?:ear|ay)s?/).last
-
else
-
unless certificate.is_ucc?
-
sub_order_items.includes(:product_variant_item).map(&:product_variant_item).detect{|item|item.is_duration?}.try(:description)
-
else
-
d=sub_order_items.includes(:product_variant_item).map(&:product_variant_item).detect{|item|item.is_domain?}.try(:description)
-
unless d.blank?
-
d=~/(\d years?)/i
-
$1
-
end
-
end
-
end
-
if unit==:years
-
years =~ /\A(\d+)/
-
$1
-
elsif unit==:days
-
case years.gsub(/[^\d]+/,"").to_i
-
when 1
-
365
-
when 2
-
730
-
when 3
-
1095
-
when 4
-
1461
-
when 5
-
1826
-
when 6,7,8,9,10
-
years.gsub(/[^\d]+/,"").to_i * 365
-
else # assume days
-
years.gsub(/[^\d]+/,"").to_i if years.include?("day")
-
end
-
elsif [:comodo_api,:sslcom_api].include? unit
-
case years.gsub(/[^\d]+/,"").to_i
-
when 1
-
365
-
when 2
-
730
-
when 90 #trial
-
90
-
when 30 #trial
-
30
-
else #no ssl can go beyond 39 months. 36 months to make adding 1 or 2 years later easier
-
unit==:comodo_api ? COMODO_SSL_MAX_DURATION : SSL_MAX_DURATION
-
end
-
else
-
years
-
end
-
end
-
end
-
1
memoize :certificate_duration
-
-
1
def renewal_certificate
-
if migrated_from_v2?
-
Certificate.map_to_legacy(preferred_v2_product_description, 'renew')
-
elsif certificate.is_free?
-
Certificate.for_sale.find_by_product "basicssl"
-
else
-
certificate
-
end
-
end
-
-
1
def mapped_certificate
-
if migrated_from_v2?
-
Certificate.map_to_legacy(preferred_v2_product_description)
-
else
-
certificate
-
end
-
end
-
-
1
def description
-
if certificate.is_ucc?
-
year = sub_order_items.map(&:product_variant_item).detect(&:is_domain?)
-
else
-
year = sub_order_items.map(&:product_variant_item).detect(&:is_duration?)
-
end
-
year.blank? ? "" : (year.value.to_i < 365 ? "#{year.value.to_i} Days" :
-
"#{year.value.to_i/365} Year") + " #{certificate.title}"
-
end
-
-
#find the desired Certificate, choose among it’s product_variant_groups, and finally choose among it’s product_variant_items
-
#
-
#change certificate_order.sub_order_item[0] to the appropriate ProductVariantItem item
-
#certificate_content.duration needs to change if not free cert
-
#
-
#take product_variant_item
-
1
def change_certificate(pvi)
-
amount = pvi.amount
-
update_attribute :amount, amount #also can update domains, server licenses, etc
-
sub_order_items[0].product_variant_item=pvi
-
sub_order_items[0].amount=amount
-
sub_order_items[0].save
-
certificate_content.duration = pvi.duration #for free certs, set to nil
-
-
#change order amount
-
line_items[0].update_attribute :cents, amount
-
Order.connection.update(
-
"UPDATE `orders` SET cents = #{line_items.map(&:cents).sum} WHERE id = #{order.id}") #override readonly
-
-
#Adjust funded account
-
ssl_account.funded_account.update_attribute :cents, amount
-
end
-
-
1
def migrated_from_v2?
-
Rails.cache.fetch("#{cache_key}/migrated_from_v2") do
-
order.try(:preferred_migrated_from_v2)
-
end
-
end
-
1
memoize "migrated_from_v2?".to_sym
-
-
1
def signup_process(cert=certificate)
-
unless skip_payment?
-
if ssl_account && ssl_account.has_role?('reseller')
-
unless cert.is_ev?
-
EXPRESS_SIGNUP_PROCESS
-
else
-
FULL_SIGNUP_PROCESS
-
end
-
else
-
FULL_SIGNUP_PROCESS
-
end
-
else
-
prepaid_signup_process(cert)
-
end
-
end
-
-
1
def self.skip_verification?(certificate)
-
certificate.skip_verification?
-
end
-
-
1
def skip_verification?
-
self.certificate.skip_verification?
-
end
-
-
1
def skip_contacts_step?
-
return false if certificate_contents.count == 1
-
if certificate && certificate.is_smime_or_client?
-
true
-
elsif Contact.optional_contacts?
-
if signed_certificate.try('is_dv?'.to_sym) && Settings.exempt_dv_contacts
-
true
-
else
-
certificate_contents.includes(:certificate_contacts).map(&:certificate_contacts).flatten.any?
-
end
-
else
-
roles = co.certificate_contacts.includes(:roles).map(&:roles).flatten.uniq
-
req_roles = CertificateContent::CONTACT_ROLES
-
(roles & req_roles).count == req_roles.count
-
end
-
end
-
-
1
def order_status
-
if is_ev?
-
"waiting for documents"
-
end
-
end
-
-
1
def prepaid_signup_process(cert=certificate)
-
if cert.admin_submit_csr?
-
NO_CSR_SIGNUP_PROCESS
-
elsif ssl_account && ssl_account.has_role?('reseller')
-
unless cert.is_ev?
-
PREPAID_EXPRESS_SIGNUP_PROCESS
-
else
-
PREPAID_FULL_SIGNUP_PROCESS
-
end
-
elsif cert.is_client?
-
PREPAID_EXPRESS_SIGNUP_PROCESS
-
else
-
PREPAID_FULL_SIGNUP_PROCESS
-
end
-
end
-
-
1
def iv_validated?
-
if get_recipient
-
iv_exists = get_team_iv
-
iv_exists && iv_exists.validated?
-
else
-
false
-
end
-
end
-
-
1
def ov_validated?
-
locked_registrant && locked_registrant.validated?
-
end
-
-
1
def iv_ov_validated?
-
iv_validated? && ov_validated?
-
end
-
-
1
def smime_client_process
-
return CLIENT_SMIME_NO_DOCS if certificate.nil?
-
registrant_types = certificate.client_smime_validations
-
-
if registrant_types == 'iv_ov'
-
iv_ov_validated? ? CLIENT_SMIME_NO_DOCS : CLIENT_SMIME_FULL
-
elsif registrant_types == 'iv'
-
(!iv_validated? or self.certificate.is_client_pro?) ? CLIENT_SMIME_IV_VALIDATE : CLIENT_SMIME_IV_VALIDATED
-
else
-
CLIENT_SMIME_NO_IV_OV
-
end
-
end
-
-
1
def get_team_iv(for_assignee=nil)
-
recipient = for_assignee ? assignee : get_recipient
-
if recipient
-
ssl_account.individual_validations.find_by(
-
user_id: (recipient.is_a?(User) ? recipient.id : recipient.user_id)
-
)
-
end
-
end
-
-
1
def get_download_cert_email
-
if certificate.is_smime_or_client?
-
get_team_iv.email
-
else
-
certificate_content.locked_registrant.email
-
end
-
end
-
-
1
def get_download_cert_salutation
-
if certificate.is_smime_or_client?
-
[get_team_iv.first_name, get_team_iv.last_name].join(' ')
-
else
-
[locked_registrant.first_name, locked_registrant.last_name].join(' ')
-
end
-
end
-
-
1
def copy_iv_ov_validation_history(type='iv')
-
iv_exists = get_team_iv
-
-
if get_recipient && iv_exists && iv_exists.validation_histories.any?
-
new_vh = iv_exists.validation_histories - validation.validation_histories
-
if locked_recipient
-
locked_recipient.validation_histories << new_vh
-
end
-
validation.validation_histories << new_vh
-
end
-
-
if type == 'iv_ov' && locked_registrant &&
-
locked_registrant.validation_histories.any?
-
new_vh = locked_registrant.validation_histories - validation.validation_histories
-
validation.validation_histories << new_vh
-
end
-
end
-
-
1
def can_validate_ov?(current_user)
-
sysadmin = current_user.is_system_admins?
-
acct_admins = current_user.is_owner? || current_user.is_account_admin?
-
acct_admins_can = !certificate_content.validated? && acct_admins && ov_validated?
-
-
(certificate.is_smime_or_client? && ( sysadmin || acct_admins_can )) ||
-
((certificate.is_ov? or certificate.is_ev?) && sysadmin)
-
end
-
-
1
def reprocess_ucc_process
-
ssl_account.invoice_required? ? REPROCES_SIGNUP_W_INVOICE : REPROCES_SIGNUP_W_PAYMENT
-
end
-
-
1
def is_express_signup?
-
!signup_process[:label].scan(EXPRESS).blank?
-
end
-
-
1
def is_express_validation?
-
validation.validation_rulings.detect(&:new?) &&
-
!signup_process[:label].scan(EXPRESS).blank?
-
end
-
-
1
def certificate_content
-
certificate_contents.last
-
end
-
1
memoize :certificate_content
-
-
1
def certificate_order_token
-
certificate_order_tokens.last
-
end
-
-
1
def generate_certificate_order_token
-
certificate_order_tokens.where(:status => nil).last
-
end
-
-
1
def phone_verified?
-
return false if locked_registrant.blank?
-
certificate_order_tokens.where(
-
status: CertificateOrderToken::DONE_STATUS,
-
phone_number: locked_registrant.country_code.blank? ?
-
('+1-' + locked_registrant.phone) :
-
('+' + locked_registrant.country_code + '-' + locked_registrant.phone)
-
-
).first
-
end
-
-
1
def registrant
-
certificate_content.registrant
-
end
-
-
1
def locked_registrant
-
certificate_content.locked_registrant
-
end
-
-
1
def csr
-
certificate_content.csr
-
end
-
-
1
def most_recent_csr
-
csrs.last || parent.try(:most_recent_csr)
-
end
-
-
1
def effective_date
-
certificate_content.try("csr").try("signed_certificate").try("effective_date")
-
end
-
-
1
def expiration_date
-
certificate_content.csr.signed_certificate.expiration_date
-
end
-
-
1
def is_expired_credit?
-
is_expired? && certificate_content.new? && created_at < 6.months.ago
-
end
-
-
1
def subject
-
Rails.cache.fetch("#{cache_key}/subject") do
-
csr=csrs.last
-
return "" if csr.blank?
-
if certificate_content.issued?
-
csr.signed_certificates.last.try(:common_name)
-
else
-
certificate_content.certificate_names.where{is_common_name==true}.last.try(:name) || csr.try(:common_name) || ""
-
end
-
end || ""
-
end
-
1
alias :common_name :subject
-
1
memoize :subject
-
-
1
def display_subject
-
csr = csrs.last
-
return if csr.blank?
-
last_signed_certificate=csr.signed_certificates.last
-
names=last_signed_certificate.subject_alternative_names unless last_signed_certificate.blank?
-
names=names.join(", ") unless names.blank?
-
names || last_signed_certificate.try(:common_name) || csr.common_name
-
end
-
1
memoize :display_subject
-
-
1
def domains
-
if certificate_contents.first.domains.kind_of?(Array)
-
certificate_contents.first.domains.flatten
-
else
-
certificate_contents.first.domains
-
end
-
end
-
-
1
def revoke!(reason, owner=nil)
-
SystemAudit.create(owner: owner, target: self, notes: reason, action: "revocation")
-
unless self.external_order_number.blank?
-
OrderNotifier.request_comodo_refund("refunds@comodo.com", self.external_order_number, reason).deliver
-
OrderNotifier.request_comodo_refund("support@ssl.com", self.external_order_number, reason, "noreply@ssl.com").deliver
-
ComodoApi.revoke_ssl(certificate_order: self, refund_reason: reason)
-
end
-
if self.notes =~ /DV#(\d+)/
-
OrderNotifier.request_comodo_refund("refunds@comodo.com", $1, reason).deliver
-
OrderNotifier.request_comodo_refund("support@ssl.com", $1, reason, "noreply@ssl.com").deliver
-
ComodoApi.revoke_ssl(refund_reason: reason, external_order_number: $1)
-
end
-
signed_certificates.each do |sc|
-
sc.revoke!(reason) # this will result in redundant calls, but will catch all signed certificates under this order
-
cc=sc.certificate_content
-
cc.revoke! if cc and !cc.revoked?
-
end
-
end
-
-
1
def wildcard_domains
-
domains.find_all{|d|d=~/\A\*\./} unless domains.blank?
-
end
-
-
1
def nonwildcard_domains
-
domains-nonwildcard_domains unless domains.blank?
-
end
-
-
# count of domains bought
-
# type can be 'wildcard', 'all'
-
1
def purchased_domains(type="nonwildcard")
-
soid = sub_order_items.find_all{|item|item.
-
product_variant_item.is_domain?}
-
case type
-
when 'all'
-
soid.sum(&:quantity)
-
when 'wildcard'
-
soid.find_all{|item|item.product_variant_item.serial=~ /wcdm/}.sum(&:quantity)
-
when 'nonwildcard'
-
soid.sum(:quantity)-soid.find_all{|item|item.product_variant_item.serial=~ /wcdm/}.sum(&:quantity)
-
end
-
end
-
-
1
def order
-
orders.last
-
end
-
-
1
def clean_up_mappings(friendly_name)
-
cac=certificate.cas_certificates.select{|c|c.ca.friendly_name =~ Regexp.new(friendly_name)}
-
certificate.cas_certificates.where{id << cac.map(&:id)}.delete_all
-
# test
-
# certificate.cas.ssl_account_or_general_default(ssl_account)
-
end
-
-
# SSL.com chained Root call
-
# DRY this up with ValidationsController#new
-
1
def domains_validated?
-
return true if certificate_content.all_domains_validated?
-
ssl_account.other_dcvs_satisfy_domain(certificate_content.certificate_names.unvalidated)
-
certificate_content.all_domains_validated?
-
end
-
-
1
def caa_validated?
-
Settings.enable_caa || true
-
end
-
-
1
def apply_for_certificate(options={})
-
if [Ca::CERTLOCK_CA,Ca::SSLCOM_CA,Ca::MANAGEMENT_CA].include?(options[:ca]) or certificate_content.ca or
-
!options[:mapping].blank?
-
if !certificate_content.infringement.empty? # possible trademark problems
-
OrderNotifier.potential_trademark(Settings.notify_address, self, certificate_content.infringement).deliver_now
-
elsif !certificate.is_server? or (domains_validated? and caa_validated?)
-
# # queue this job due to CAA lookups
-
# if certificate_names.count > 10 and not options[:mapping].try(:profile_name)=~/EV/
-
# unless certificate_content.pending_issuance?
-
# SslcomCaApi.delay.apply_for_certificate(self, options)
-
# certificate_content.pend_issuance!
-
# end
-
# else
-
SslcomCaApi.apply_for_certificate(self, options)
-
# end
-
end
-
else
-
ComodoApi.apply_for_certificate(self, options) if ca_name=="comodo"
-
end if remaining_days>0
-
end
-
-
1
def retrieve_ca_cert(email_customer=true)
-
if external_order_number && certificate_content.ca.blank? &&
-
!ca_certificate_requests.empty? && ca_certificate_requests.first.success? && !rejected?
-
retrieve=ComodoApi.collect_ssl(self)
-
if retrieve.response_code==2
-
csr.signed_certificates.create(body: retrieve.certificate, email_customer: email_customer)
-
self.orphaned_certificate_contents remove: true
-
elsif retrieve.response_code==-20
-
self.reject!
-
end
-
end
-
end
-
-
1
def self.retrieve_ca_certs(start, finish, options={})
-
Sandbox.find_by_host(options[:db]).use_database unless options[:db].blank?
-
cos=Csr.range(start, finish).pending.map(&:certificate_orders).flatten.uniq
-
#cannot reference co.retrieve_ca_cert(true) because it filters out issued certificate_contents which contain the external_order_number
-
cos.each{|co|CertificateOrder.unscoped.find_by_ref(co.ref).retrieve_ca_cert(true)}
-
SystemAudit.create(owner: nil, target: nil,
-
notes: "",
-
action: "CertificateOrder#retrieve_ca_certs(#{start},#{finish},#{options.to_s})")
-
end
-
-
1
def to_param
-
ref
-
end
-
-
1
def last_dcv_sent
-
return if csr.blank?
-
dcvs=csr.domain_control_validations
-
(%w(http https).include?(dcvs.last.try(:dcv_method))) ? dcvs.last : dcvs.last_sent
-
end
-
-
-
1
def self.to_api_string(options={})
-
domain = options[:domain_override] || "https://sws-test.sslpki.com"
-
options[:action]="create_ssl" if options[:action].blank?
-
case options[:action]
-
when /create_ssl/
-
'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X POST -d "'+
-
{account_key: "",
-
secret_key: "",
-
product: options[:certificate].api_product_code,
-
period: options[:period]}.to_json.gsub("\"","\\\"") +
-
"\" #{domain}/certificates"
-
when /create_code_signing/
-
'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X POST -d "'+
-
{account_key: "",
-
secret_key: "",
-
product: options[:certificate].api_product_code,
-
period: options[:period]}.to_json.gsub("\"","\\\"") +
-
"\" #{domain}/certificates"
-
when /create_code_signing/
-
'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X POST -d "'+
-
{account_key: "",
-
secret_key: "",
-
product: options[:certificate].api_product_code,
-
period: options[:period]}.to_json.gsub("\"","\\\"") +
-
"\" #{domain}/certificates"
-
end
-
end
-
-
1
def exceeds_br_duration?
-
certificate_duration(:days).to_i > certificate.max_duration
-
end
-
-
1
def to_api_string(options={action: "update"})
-
domain = options[:domain_override] || "https://sws-test.sslpki.com"
-
api_contacts, api_domains, cc, registrant_params = base_api_params
-
if ssl_account.api_credential
-
account_key = (options[:show_credentials] || options[:current_user].try("is_system_admins?".to_sym)) ? ssl_account.api_credential.account_key : "[REDACTED]"
-
secret_key = (options[:show_credentials] || options[:current_user].try("is_system_admins?".to_sym)) ? ssl_account.api_credential.secret_key : "[REDACTED]"
-
end
-
case options[:action]
-
when /update_dcv/
-
# registrant_params.merge!(api_domains).merge!(api_contacts)
-
api_params={account_key: account_key,
-
secret_key: secret_key,
-
domains: api_domains}
-
options[:caller].blank? ?
-
'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X PUT -d "'+
-
api_params.to_json.gsub("\"","\\\"") + "\" #{domain}/certificate/#{self.ref}" : api_params
-
when /update/
-
api_params={account_key: account_key,
-
secret_key: secret_key,
-
server_software: cc.server_software_id.to_s,
-
domains: api_domains,
-
contacts: api_contacts,
-
csr: certificate_content.csr.body}.merge!(registrant_params)
-
# registrant_params.merge!(api_domains).merge!(api_contacts)
-
options[:caller].blank? ? 'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X PUT -d "'+
-
api_params.to_json.gsub("\"","\\\"") + "\" #{domain}/certificate/#{self.ref}" : api_params
-
when /revoke/
-
api_params={account_key: account_key,
-
secret_key: secret_key,
-
reason: "development test",
-
serials:signed_certificates.map(&:serial),
-
ref: self.ref}
-
options[:caller].blank? ? 'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X DELETE -d "'+
-
api_params.to_json.gsub("\"","\\\"") + "\" #{domain}/certificate/#{self.ref}" : api_params
-
when /create_w_csr/
-
api_params={account_key: account_key,
-
secret_key: secret_key,
-
product: certificate.api_product_code,
-
period: certificate_duration(:comodo_api).to_s,
-
server_software: cc.server_software_id.to_s,
-
domains: api_domains,
-
contacts: api_contacts,
-
csr: certificate_content.csr.body}.merge!(registrant_params)
-
options[:caller].blank? ? 'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X POST -d "'+
-
api_params.to_json.gsub("\"","\\\"") + "\" #{domain}/certificates" : api_params
-
when /create/
-
api_params={account_key: account_key,
-
secret_key: secret_key,
-
product: certificate.api_product_code,
-
period: certificate_duration(:comodo_api).to_s,
-
domains: api_domains}
-
options[:caller].blank? ? 'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X POST -d "'+
-
api_params.to_json.gsub("\"","\\\"") + "\" #{domain}/certificates" : api_params
-
when /show/
-
api_params={account_key: account_key,
-
secret_key: secret_key,
-
query_type: ("all_certificates" unless signed_certificate.blank?), show_subscriber_agreement: "Y",
-
response_type: ("individually" unless signed_certificate.blank?)}
-
options[:caller].blank? ? 'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X GET -d "'+
-
api_params.to_json.gsub("\"","\\\"") + "\" #{domain}/certificate/#{self.ref}" : api_params
-
when /index/
-
api_params={account_key: account_key,
-
secret_key: secret_key,
-
per_page: "10", page: "1"}
-
options[:caller].blank? ? 'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X GET -d "'+
-
api_params.to_json.gsub("\"","\\\"") + "\" #{domain}/certificates" : api_params
-
when /dcv_emails/
-
api_params={account_key: account_key,
-
secret_key: secret_key}.
-
merge!(certificate.is_ucc? ? {domains: certificate_content.domains} : {domain: csr.common_name})
-
options[:caller].blank? ? 'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X GET -d "'+
-
api_params.to_json.gsub("\"","\\\"") + "\" #{domain}/certificates/validations/email" : api_params
-
when /dcv_methods_wo_csr/
-
api_params={account_key: account_key,
-
secret_key: secret_key}
-
options[:caller].blank? ? 'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X GET -d "'+
-
api_params.to_json.gsub("\"","\\\"") + "\" #{domain}/certificate/#{ref}/validations/methods" : api_params
-
when /dcv_methods_w_csr/
-
api_params={account_key: account_key,
-
secret_key: secret_key,
-
csr: certificate_content.csr.body}
-
options[:caller].blank? ? 'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X POST -d "'+
-
api_params.to_json.gsub("\"","\\\"") + "\" #{domain}/certificates/validations/csr_hash" : api_params
-
end
-
end
-
-
1
def domains_and_common_name
-
certificate_content.domains_and_common_name
-
end
-
-
1
def base_api_params
-
cc = certificate_content
-
r = cc.registrant
-
registrant_params = r.blank? ? {} :
-
{organization_name: r.company_name,
-
organization_unit_name: r.department,
-
post_office_box: r.po_box,
-
street_address_1: r.address1,
-
street_address_2: r.address2,
-
street_address_3: r.address3,
-
locality_name: r.city,
-
state_or_province_name: r.state,
-
postal_code: r.postal_code,
-
country_name: r.country}
-
api_domains = {}
-
if !cc.domains.blank?
-
cc.certificate_names.includes(:domain_control_validations).find_by_domains(cc.domains.flatten+[common_name]).each {|cn|
-
if cn
-
api_domains.merge!(cn.name.to_sym => {dcv:
-
cn.domain_control_validations.last_method.try(:method_for_api) ||
-
ApiCertificateCreate_v1_4::DEFAULT_DCV_METHOD })
-
end
-
}
-
elsif cc.csr and certificate.is_server?
-
api_domains.merge!(cc.csr.common_name.to_sym => {dcv: "#{last_dcv_sent ? last_dcv_sent.method_for_api : 'http_csr_hash'}"})
-
end
-
api_contacts = {}
-
CertificateContent::CONTACT_ROLES.each do |role|
-
contact=cc.certificate_contacts.find do |certificate_contact|
-
if certificate_contact.roles.include?(role)
-
api_contact={}
-
(CertificateContent::RESELLER_FIELDS_TO_COPY+['country']).each do |field|
-
api_contact.merge! field.to_sym => "#{certificate_contact.send(field.to_sym)}"
-
end
-
api_contacts.merge! role.to_sym => api_contact
-
end
-
end
-
end
-
return api_contacts, api_domains, cc, registrant_params
-
end
-
1
memoize :base_api_params
-
-
1
def add_renewal(ren)
-
unless ren.blank?
-
self.renewal_id=CertificateOrder.find_by_ref(ren).id
-
end
-
end
-
-
1
def self.link_renewal(old, new)
-
CertificateOrder.find_by_ref(new).update_column :renewal_id, CertificateOrder.find_by_ref(old).id
-
end
-
-
=begin
-
Renews certificate orders and also handles the billing aspects
-
Use the order's credit card, then the most recent successfully card card
-
Renew for the same number of years as original order
-
If order is over a certain amount, notify customer first and let them know they do not need to
-
do anything
-
=end
-
# notify can be "none", "success", or "all"
-
1
def do_auto_renew(notify="success")
-
#does a credit already exists for this cert order
-
if (renewal.blank? || renewal_attempts_old?) && (auto_renew.blank? || auto_renew=="scheduled")
-
purchase_renewal(notify)
-
end
-
end
-
-
1
def renewal_attempts_old?
-
renewal_attempts.blank? ? true : renewal_attempts.last.created_at < RENEWAL_DATE_CUTOFF
-
end
-
-
1
def validation_methods
-
validation.validation_rules.map(&:applicable_validation_methods).
-
flatten.uniq
-
end
-
-
1
def validation_rules_satisfied?
-
certificate_content.validated?
-
end
-
-
1
def is_unused_credit?
-
certificate_content.try("new?") && workflow_state=='paid'
-
end
-
-
1
def is_unused?
-
certificate_content.try("new?") && (workflow_state=='paid' || workflow_state=='refunded')
-
end
-
-
1
def is_prepaid?
-
preferred_payment_order=='prepaid'
-
end
-
-
1
def skip_payment?
-
!!(is_prepaid? || (certificate_content && certificate_content.preferred_reprocessing?))
-
end
-
-
1
def is_intranet?
-
certificate_content.csr.is_intranet? if certificate_content.try(:csr)
-
end
-
-
1
def server_software
-
certificate_content.server_software || ServerSoftware.find(1)
-
end
-
1
alias :software :server_software
-
-
1
def is_open_ssl?
-
[3, 4, 35, 39].include? software.id
-
end
-
-
1
def is_apache?
-
[3, 4].include? software.id
-
end
-
-
1
def is_amazon_balancer?
-
[39].include? software.id
-
end
-
-
1
def is_iis?
-
[18, 19, 20].include? software.id
-
end
-
-
1
def is_nginx?
-
[37].include? software.id
-
end
-
-
1
def is_cpanel?
-
[35].include? software.id
-
end
-
-
1
def is_red_hat?
-
[29].include? software.id
-
end
-
-
1
def is_plesk?
-
[25].include? software.id
-
end
-
-
1
def is_heroku?
-
[38].include? software.id
-
end
-
-
1
def has_bundle?
-
!!(is_red_hat? || is_plesk? || is_heroku? || is_amazon_balancer?)
-
end
-
-
1
def bundle_name
-
if has_bundle?
-
if is_apache? or is_amazon_balancer?
-
'Apache bundle (SSLCACertificateFile)'
-
elsif is_red_hat? || is_plesk?
-
'ca bundle (Apache SSLCACertificateFile)'
-
elsif is_heroku?
-
'ca bundle for Heroku'
-
end
-
else
-
""
-
end
-
end
-
-
1
def status
-
if certificate_content.new?
-
if certificate.is_code_signing?
-
"waiting on registrant or organization information"
-
else
-
"unused. waiting on certificate signing request (csr)"
-
end
-
elsif certificate_content.expired?
-
'n/a'
-
else
-
case certificate_content.workflow_state
-
when "csr_submitted"
-
"waiting on registrant information from customer"
-
when "info_provided"
-
"waiting on contacts information from customer"
-
when "reprocess_requested"
-
"reissue requested. waiting on certificate signing request (csr)from customer"
-
when "contacts_provided"
-
"waiting on validation from customer"
-
when "pending_validation", "validated"
-
last_sent=csr.try(:last_dcv)
-
if last_sent.blank? or (certificate.is_evcs? and validation_histories.count>0)
-
'validating, please wait' #assume intranet
-
elsif %w(http https cname http_csr_hash https_csr_hash cname_csr_hash).include?(last_sent.try(:dcv_method))
-
'validating, please wait'
-
else
-
"waiting validation email response from customer"
-
end
-
when "issued"
-
if certificate_content.expiring?
-
if renewal && renewal.paid?
-
"renewed. see #{renewal.ref} for renewal"
-
else
-
"expiring. renew soon"
-
end
-
else
-
"issued"
-
end
-
when "canceled"
-
end
-
end
-
end
-
-
# depending on the server software type we will bundle different root and intermediate certs
-
# override is a target server software other than the default one for this order
-
1
def bundled_cert_names(override={})
-
if self.ca == CA_CERTIFICATES[:SSLcomSHA2]
-
if (is_open_ssl? && override[:components].blank?) || override[:is_open_ssl]
-
#attach bundle
-
Certificate::BUNDLES[:comodo][:sha2_sslcom_2014][:labels].select do |k,v|
-
if signed_certificate.try("is_ev?".to_sym)
-
k=="sslcom_ev_ca_bundle#{ascending_root(override)}.txt"
-
elsif signed_certificate.try("is_dv?".to_sym)
-
k=="sslcom_addtrust_ca_bundle#{ascending_root(override)}.txt"
-
elsif signed_certificate.try("is_ov?".to_sym)
-
k=="sslcom_high_assurance_ca_bundle#{ascending_root(override)}.txt"
-
elsif certificate.is_ev?
-
k=="sslcom_ev_ca_bundle#{ascending_root(override)}.txt"
-
elsif certificate.is_essential_ssl?
-
k=="sslcom_addtrust_ca_bundle#{ascending_root(override)}.txt"
-
else
-
k=="sslcom_high_assurance_ca_bundle#{ascending_root(override)}.txt"
-
end
-
end.map{|k,v|k}
-
else
-
if signed_certificate.try("is_ev?".to_sym)
-
Certificate::BUNDLES[:comodo][:sha2_sslcom_2014][:contents]["sslcom_ev#{'_amazon' if is_amazon_balancer? || ["amazon","iis"].include?(override[:server])}.txt"]
-
elsif signed_certificate.try("is_dv?".to_sym)
-
Certificate::BUNDLES[:comodo][:sha2_sslcom_2014][:contents]["sslcom_dv#{'_amazon' if is_amazon_balancer? || ["amazon","iis"].include?(override[:server])}.txt"]
-
elsif signed_certificate.try("is_ov?".to_sym)
-
Certificate::BUNDLES[:comodo][:sha2_sslcom_2014][:contents]["sslcom_ov#{'_amazon' if is_amazon_balancer? || ["amazon","iis"].include?(override[:server])}.txt"]
-
elsif certificate.is_ev?
-
Certificate::BUNDLES[:comodo][:sha2_sslcom_2014][:contents]["sslcom_ev#{'_amazon' if is_amazon_balancer? || ["amazon","iis"].include?(override[:server])}.txt"]
-
elsif certificate.is_essential_ssl?
-
Certificate::BUNDLES[:comodo][:sha2_sslcom_2014][:contents]["sslcom_dv#{'_amazon' if is_amazon_balancer? || ["amazon","iis"].include?(override[:server])}.txt"]
-
else
-
Certificate::BUNDLES[:comodo][:sha2_sslcom_2014][:contents]["sslcom_ov#{'_amazon' if is_amazon_balancer? || ["amazon","iis"].include?(override[:server])}.txt"]
-
end
-
end
-
else
-
if is_open_ssl? && override[:components].blank?
-
#attach bundle
-
Certificate::COMODO_BUNDLES.select do |k,v|
-
if certificate.serial=~/256sslcom/
-
if signed_certificate.try("is_ev?".to_sym)
-
k=="sslcom_ev_ca_bundle#{ascending_root(override)}.txt"
-
#elsif certificate.is_free?
-
# k=="sslcom_free_ca_bundle.txt"
-
elsif signed_certificate.try("is_dv?".to_sym)
-
k=="sslcom_addtrust_ca_bundle#{ascending_root(override)}.txt"
-
elsif signed_certificate.try("is_ov?".to_sym)
-
k=="sslcom_high_assurance_ca_bundle#{ascending_root(override)}.txt"
-
elsif certificate.is_ev?
-
k=="sslcom_ev_ca_bundle#{ascending_root(override)}.txt"
-
#elsif certificate.is_free?
-
# k=="sslcom_free_ca_bundle.txt"
-
elsif certificate.is_essential_ssl?
-
k=="sslcom_addtrust_ca_bundle#{ascending_root(override)}.txt"
-
else
-
k=="sslcom_high_assurance_ca_bundle#{ascending_root(override)}.txt"
-
end
-
elsif certificate.comodo_product_id==342
-
k=="free_ssl_ca_bundle#{ascending_root(override)}.txt"
-
elsif certificate.comodo_product_id==43
-
k=="trial_ssl_ca_bundle#{ascending_root(override)}.txt"
-
else
-
k=="ssl_ca_bundle#{ascending_root(override)}.txt"
-
end
-
end.map{|k,v|k}
-
else
-
Certificate::COMODO_BUNDLES.select do |k,v|
-
if certificate.serial=~/256sslcom/
-
if signed_certificate.try("is_ev?".to_sym)
-
%w(SSLcomPremiumEVCA.crt COMODOAddTrustServerCA.crt AddTrustExternalCARoot.crt).include? k
-
elsif signed_certificate.try("is_dv?".to_sym)
-
%w(SSLcomAddTrustSSLCA.crt AddTrustExternalCARoot.crt).include? k
-
elsif signed_certificate.try("is_ov?".to_sym)
-
%w(SSLcomHighAssuranceCA.crt AddTrustExternalCARoot.crt).include? k
-
elsif certificate.is_ev?
-
%w(SSLcomPremiumEVCA.crt COMODOAddTrustServerCA.crt AddTrustExternalCARoot.crt).include? k
-
elsif certificate.is_essential_ssl?
-
%w(SSLcomAddTrustSSLCA.crt AddTrustExternalCARoot.crt).include? k
-
else
-
%w(SSLcomHighAssuranceCA.crt AddTrustExternalCARoot.crt).include? k
-
end
-
elsif [342, 343].include? certificate.comodo_product_id
-
%w(UTNAddTrustSGCCA.crt EssentialSSLCA_2.crt ComodoUTNSGCCA.crt AddTrustExternalCARoot.crt).include? k
-
elsif certificate.comodo_product_id==337 #also maybe 410 (evucc) we'll get there when we place that order
-
%w(COMODOExtendedValidationSecureServerCA.crt COMODOAddTrustServerCA.crt AddTrustExternalCARoot.crt).include? k
-
elsif certificate.comodo_product_id==361
-
%w(EntrustSecureServerCA.crt USERTrustLegacySecureServerCA.crt).include? k
-
else
-
%w(SSLcomHighAssuranceCA.crt AddTrustExternalCARoot.crt).include? k
-
end
-
end.map{|k,v|k}
-
end
-
end
-
end
-
-
# @param [Hash] override
-
1
def ascending_root(override)
-
'_amazon' if is_amazon_balancer? || override[:server]=="amazon" || override[:ascending_root]==true
-
end
-
-
1
def bundled_cert_dir
-
if self.ca == CA_CERTIFICATES[:SSLcomSHA2]
-
Settings.intermediate_certs_path+Certificate::BUNDLES[:comodo][:sha2_sslcom_2014][:dir]+"/"
-
else
-
Settings.intermediate_certs_path
-
end
-
end
-
-
# @return [String]
-
1
def ca_name
-
if common_name =~ /impulshcs/
-
"ssl.com"
-
else
-
"comodo"
-
end
-
end
-
-
1
def description_with_tier(target_order=nil)
-
return description if certificate.reseller_tier.blank?
-
tier_label = if target_order && target_order.reseller_tier
-
target_order.reseller_tier.label
-
else
-
certificate.reseller_tier.label
-
end
-
description + " (Tier #{tier_label} Reseller)"
-
end
-
-
1
def validation_stage_checkout_in_progress?
-
certificate_content.contacts_provided?
-
end
-
-
1
CertificateContent::CONTACT_ROLES.each do |role|
-
4
define_method("#{role}_contact") do
-
certificate_content.send("#{role}_contact".intern)
-
end
-
end
-
-
1
%W(processed receipt confirmation).each do |et|
-
3
define_method("#{et}_recipients") do
-
[].tap do |addys|
-
addys << ssl_account.reseller.email if
-
ssl_account.is_registered_reseller? &&
-
ssl_account.send("preferred_#{et}_include_reseller?")
-
et_tmp = (et=="processed" ? "processed_certificate" : et)
-
addys << ssl_account.send("preferred_#{et_tmp}_recipients") unless
-
ssl_account.send("preferred_#{et_tmp}_recipients")=="0"
-
addys << administrative_contact.email if
-
administrative_contact &&
-
ssl_account.send("preferred_#{et}_include_cert_admin?")
-
ct = (et=="processed" ? "tech" : "bill")
-
addys << billing_contact.email if
-
billing_contact && !et=="processed" &&
-
ssl_account.send("preferred_#{et}_include_cert_#{ct}?")
-
addys << technical_contact.email if
-
technical_contact && et=="processed" &&
-
ssl_account.send("preferred_#{et}_include_cert_#{ct}?")
-
end.uniq
-
end
-
end
-
-
# def receipt_recipients
-
# returning addys = [] do
-
# addys << ssl_account.reseller.email if
-
# ssl_account.is_registered_reseller? &&
-
# ssl_account.preferred_receipt_include_reseller?
-
# addys << ssl_account.preferred_receipt_recipients unless
-
# ssl_account.preferred_receipt_recipients.empty?
-
# addys << administrative_contact.email if
-
# ssl_account.preferred_receipt_include_cert_admin?
-
# addys << billing_contact.email if
-
# ssl_account.preferred_receipt_include_cert_bill?
-
# addys.uniq!
-
# end
-
# end
-
-
1
def certificate_chain_names
-
parse_certificate_chain.transpose[0]
-
end
-
-
1
def certificate_chain_types
-
parse_certificate_chain.transpose[1]
-
end
-
-
1
def parse_certificate_chain
-
preferred_certificate_chain.split(",").
-
map(&:strip).map{|a|a.split(":")}
-
end
-
-
1
def friendly_common_name
-
signed_certificate.nonidn_friendly_common_name
-
end
-
-
1
def request_csr_from
-
-
end
-
-
1
def v2_line_items
-
preferred_v2_line_items.split('|') unless preferred_v2_line_items.blank?
-
end
-
-
1
def v2_line_items=(line_items)
-
self.preferred_v2_line_items = line_items.join('|')
-
end
-
-
1
def options_for_ca(options={})
-
{}.tap do |params|
-
cc=(options[:certificate_content] || certificate_content)
-
cc.csr.tap do |csr|
-
update_attribute(:ca, CA_CERTIFICATES[:SSLcomSHA2]) if self.ca.blank?
-
if options[:new].blank? && (csr.sent_success || external_order_number)
-
#assume reprocess, will need to look at ucc more carefully
-
params.merge!(
-
'orderNumber' => external_order_number,
-
'csr' => csr.to_api,
-
'prioritiseCSRValues' => 'N',
-
'isCustomerValidated' => 'N',
-
'responseFormat' => 1,
-
'showCertificateID' => 'N',
-
'foreignOrderNumber' => ref,
-
'countryName'=>csr.country,
-
'uniqueValue'=>csr.unique_value
-
)
-
last_sent = csr.domain_control_validations.last_method
-
build_comodo_dcv(last_sent, params, options)
-
else
-
params.merge!(
-
'test' => (is_test || !(Rails.env =~ /production/i)) ? "Y" : "N",
-
'product' => options[:product] || mapped_certificate.comodo_product_id.to_s,
-
'serverSoftware' => cc.comodo_server_software_id.blank? ? ServerSoftware::OTHER :
-
cc.comodo_server_software_id.to_s,
-
'csr' => csr.to_api,
-
'prioritiseCSRValues' => 'N',
-
'isCustomerValidated' => 'N',
-
'responseFormat' => 1,
-
'showCertificateID' => 'N',
-
'foreignOrderNumber' => ref,
-
'uniqueValue'=>csr.unique_value
-
)
-
last_sent = csr.last_dcv
-
#43 is the old comodo 30 day trial
-
#look at certificate_duration for more guidance, i don't think the following is ucc safe
-
days = certificate_duration(:comodo_api)
-
# temporary for a certain customer wanting to move over a number of domains to ssl.com
-
if [Certificate::COMODO_PRODUCT_MAPPINGS["free"], 43].include?(
-
mapped_certificate.comodo_product_id) #trial cert does not specify duration
-
params.merge!('days' => (days).to_s)
-
else
-
params.merge!('days' => (days+csr.days_left).to_s)
-
end
-
build_comodo_dcv(last_sent, params, options)
-
fill_csr_fields(params, cc.registrant)
-
unless csr.csr_override.blank?
-
fill_csr_fields params, csr.csr_override
-
end
-
if false #TODO make country override option
-
override_params(params) #essentialssl
-
end
-
if certificate.is_wildcard?
-
params.merge!('servers' => server_licenses.to_s || '1')
-
end
-
end
-
#ssl.com Sub CA certs
-
set_comodo_subca(params,options)
-
if certificate.is_ev?
-
params.merge!('joiCountryName'=>(cc.csr.csr_override || cc.registrant).country)
-
params.merge!('joiLocalityName'=>(cc.csr.csr_override || cc.registrant).city)
-
params.merge!('joiStateOrProvinceName'=>(cc.csr.csr_override || cc.registrant).state)
-
end
-
if certificate.is_ucc?
-
params.merge!(
-
'primaryDomainName'=>csr.common_name.downcase,
-
'maxSubjectCNs'=>1
-
)
-
end
-
end
-
end
-
end
-
-
1
def override_params(options)
-
options["countryName"]="US"
-
options["prioritiseCSRValues"]="N"
-
# options["product"]=301 #essentialssl
-
# options.merge!('caCertificateID' => 401) #essentialssl
-
end
-
-
1
def build_comodo_dcv(last_sent=(csr.domain_control_validations.last_method || csr.last_dcv), params={}, options={})
-
if certificate.is_ucc?
-
dcv_methods_for_comodo=[]
-
domains_for_comodo=(options[:certificate_content] || self.certificate_content).all_domains
-
certificate_contents.first.certificate_names.
-
includes(:domain_control_validations).where{name >> domains_for_comodo}.each do |cn|
-
last = cn.try(:last_dcv_for_comodo)
-
dcv_methods_for_comodo << (last.blank? ? ApiCertificateCreate_v1_4::DEFAULT_DCV_METHOD_COMODO : last)
-
end
-
params.merge!('domainNames' => domains_for_comodo.join(","))
-
params.merge!('dcvEmailAddresses' => dcv_methods_for_comodo.join(",")) if (dcv_methods_for_comodo && dcv_methods_for_comodo.count==domains_for_comodo.count)
-
else
-
if last_sent.blank? || last_sent.dcv_method=="http"
-
params.merge!('dcvMethod' => "HTTP_CSR_HASH")
-
elsif last_sent.dcv_method=="https"
-
params.merge!('dcvMethod' => "HTTPS_CSR_HASH")
-
elsif last_sent.try("is_eligible_to_send?")
-
params.merge!('dcvEmailAddress' => last_sent.email_address)
-
last_sent.send_dcv! unless last_sent.sent_dcv?
-
end
-
end
-
end
-
-
# Creates a new external ca order history by deleting the old external order id and requests thus allowing us
-
# to start a new history with comodo for an existing ssl.com cert order
-
# useful in the event Comodo take forever to make changes to an existing order (and sometimes cannot) so we
-
# just create a new one and have the old one refunded
-
1
def reset_ext_ca_order
-
csrs.compact.map(&:sent_success).flatten.uniq.each{|a|a.delete}
-
cc=certificate_content
-
cc.preferred_reprocessing = false
-
cc.save validation: false
-
end
-
-
1
def change_ext_ca_order(new_number)
-
ss=csrs.compact.map(&:sent_success).flatten.last
-
ss.update_column :response, ss.response.gsub(external_order_number, new_number.to_s)
-
update_column :external_order_number, new_number
-
end
-
-
# Resets this order as if it never processed
-
# <tt>complete</tt> - removes the certificate_content (and it's csr and other properties)
-
# <tt>ext_ca_orders</tt> - removes the external calls history to comodo for this order
-
1
def reset(complete=false,ext_ca_orders=false)
-
self.reset_ext_ca_order if ext_ca_orders
-
self.certificate_content.csr.delete unless certificate_content.csr.blank?
-
-
self.start_over!(complete) unless ['canceled', 'revoked'].
-
include?(self.certificate_content.workflow_state)
-
end
-
-
# Removes any certificate_contents that were not processed, except the last one
-
1
def orphaned_certificate_contents(options={})
-
cc_count = self.certificate_contents.count
-
return nil if cc_count <= 1
-
ccs = []
-
certificate_contents.each_with_index do |cc, i|
-
next if i == cc_count-1 # ignore the most recent certificate_content
-
if (cc.csr.blank? || cc.csr.signed_certificate.blank?)
-
if options[:remove]
-
cc.destroy
-
else
-
ccs << cc
-
end
-
end
-
end
-
ccs unless options[:remove]
-
end
-
-
1
def self.remove_all_orphaned
-
self.find_each{|co|co.orphaned_certificate_contents remove: true}
-
end
-
-
# Removes the last certificate_content in the event it was a mistake
-
1
def remove_last_certificate_content
-
self.certificate_content.destroy if self.certificate_contents.count > 1
-
end
-
-
1
def external_order_number_meta(options={})
-
if notes =~ /(DV|EV|OV)\#\d+/
-
if options[:external_order_number] && m = notes.match(/(DV|EV|OV)\##{options[:external_order_number]}/)
-
return m[1] unless m.blank?
-
elsif options[:validation_type] && m = notes.match(/#{options[:validation_type]}\#(\d+)/)
-
return m[1] unless m.blank?
-
else
-
external_order_number && m = notes.match(/(DV|EV|OV)\##{external_order_number}/)
-
return m[1] unless m.blank?
-
end
-
end
-
end
-
-
1
def sent_success_count
-
sent_success_map = csrs.map(&:sent_success)
-
sent_success_map.flatten.compact.uniq.count if
-
csrs && !sent_success_map.blank?
-
end
-
-
# Get the most recent certificate_id (useful for UCC replacements)
-
1
def external_certificate_id
-
sent_success_map = csrs.map(&:sent_success)
-
sent_success_map.flatten.compact.uniq.first.certificate_id if
-
csrs && !sent_success_map.blank? &&
-
sent_success_map.flatten.compact.uniq.first
-
# csrs.sent_success.order_number if csrs && csrs.sent_success
-
end
-
-
1
def transfer_certificate_content(certificate_content)
-
self.site_seal.conditionally_activate! unless self.site_seal.conditionally_activated?
-
cc = self.certificate_content
-
cc.domains=certificate_content.domains
-
if certificate_content.preferred_reprocessing?
-
self.certificate_contents << certificate_content
-
certificate_content.create_registrant(cc.registrant.attributes.except(*ID_AND_TIMESTAMP)) if cc.registrant
-
cc.certificate_contacts.each do |contact|
-
certificate_content.certificate_contacts << CertificateContact.new(contact.attributes.except(*ID_AND_TIMESTAMP))
-
end
-
cc = self.certificate_content
-
else
-
cc.signing_request = certificate_content.signing_request
-
cc.server_software = certificate_content.server_software
-
cc.agreement = certificate_content.agreement #backwards compatibility with older certificate_content objects
-
end
-
if cc.new?
-
cc.submit_csr!
-
elsif cc.validated? || cc.pending_validation?
-
cc.pend_validation! if cc.validated?
-
end
-
cc
-
end
-
-
1
def all_domains
-
certificate_content.all_domains
-
end
-
-
1
def change_ssl_account!(acct_number)
-
sa = SslAccount.find_by_acct_number acct_number
-
sa.orders << self.order
-
sa.certificate_orders << self
-
end
-
-
1
def valid_recipients_list
-
return receipt_recipients unless receipt_recipients.is_a? Array
-
receipt_recipients.map(&:split).compact.flatten.uniq
-
end
-
-
1
def validating_domains
-
cns = certificate_content.certificate_names
-
(certificate.is_ucc? ? cns : [cns.last])
-
end
-
-
1
def domains_validated
-
mdc_validation = ComodoApi.mdc_status(self)
-
ds = mdc_validation.domain_status
-
validated=[]
-
validating_domains.each_with_index do |cn,i|
-
if ds and ds[cn.name]
-
name=ds[cn.name]
-
validated << cn if (name && name["status"]=~/validated/i)
-
end
-
end
-
return validated
-
end
-
-
1
def all_domains_validated?
-
if certificate_content.ca_id
-
certificate_content.all_domains_validated?
-
else
-
domains_validated.count==validating_domains.count
-
end
-
end
-
-
1
def to_api_retrieve(result, options)
-
result.order_date = self.created_at
-
result.order_status = self.status
-
result.registrant = self.certificate_content.registrant.to_api_query if (self.certificate_content && self.certificate_content.registrant)
-
result.contacts = self.certificate_content.certificate_contacts if (self.certificate_content && self.certificate_content.certificate_contacts)
-
result.validations = result.validations_from_comodo(self) if external_order_number #'validations' kept executing twice so it was renamed to 'validations_from_comodo'
-
result.description = self.description
-
result.product = self.certificate.api_product_code
-
result.product_name = self.certificate.product
-
result.subscriber_agreement = self.certificate.subscriber_agreement_content if result.show_subscriber_agreement =~ /[Yy]/
-
result.external_order_number = self.ext_customer_ref
-
result.server_software = self.server_software.id if self.server_software
-
-
if self.certificate.is_ucc?
-
result.domains_qty_purchased = self.purchased_domains('all').to_s
-
result.wildcard_qty_purchased = self.purchased_domains('wildcard').to_s
-
else
-
result.domains_qty_purchased = "1"
-
result.wildcard_qty_purchased = self.certificate.is_wildcard? ? "1" : "0"
-
end
-
-
if (self.signed_certificate && result.query_type != "order_status_only")
-
result.certificates =
-
case options[:format]
-
when "end_entity"
-
self.signed_certificate.x509_certificates.first.to_s
-
when "nginx"
-
self.signed_certificate.to_nginx(false,order: options[:order])
-
else
-
self.signed_certificate.to_format(response_type: result.response_type, #assume comodo issued cert
-
response_encoding: result.response_encoding) || self.signed_certificate.to_nginx
-
end
-
result.common_name = self.signed_certificate.common_name
-
result.subject_alternative_names = self.signed_certificate.subject_alternative_names
-
result.effective_date = self.signed_certificate.effective_date
-
result.expiration_date = self.signed_certificate.expiration_date
-
result.algorithm = self.signed_certificate.is_SHA2? ? "SHA256" : "SHA1"
-
# result.site_seal_code = ERB::Util.json_escape(ApplicationController.new.render_to_string(
-
# partial: 'site_seals/site_seal_code.html.haml',
-
# locals: {co: self},
-
# layout: false
-
# ))
-
elsif (self.csr)
-
result.certificates = ""
-
result.common_name = self.csr.common_name
-
end
-
end
-
-
1
def renew_billing?
-
co = self.parent
-
return false if co.nil?
-
ucc = co.certificate.is_ucc? && (co.certificate.is_premium_ssl? !=0)
-
ucc && co.certificate_content.expiring? && co.renewal && co.renewal.paid?
-
end
-
-
1
def certificate_contents_ref_label_switch
-
certificate_contents.each{|cc|
-
unless cc.ref=~/^co-/
-
ref = cc.ref
-
cc.ref=cc.label
-
cc.label=ref
-
cc.save
-
end
-
}
-
end
-
-
1
private
-
-
1
def fill_csr_fields(options, obj)
-
unless obj.blank?
-
f= {'organizationName' => obj.company_name,
-
'organizationalUnitName' => obj.department,
-
'postOfficeBox' => obj.po_box,
-
'streetAddress1' => obj.address1,
-
'streetAddress2' => obj.address2,
-
'streetAddress3' => obj.address3,
-
'localityName' => obj.city,
-
'stateOrProvinceName' => obj.state,
-
'postalCode' => obj.postal_code,
-
'countryName' => obj.country}
-
options.merge!(f.each{|k,v|f[k]=CGI.escape(v) unless v.blank?})
-
end
-
end
-
-
1
def post_process_csr
-
certificate_content.submit_csr!
-
if ssl_account.is_registered_reseller?
-
OrderNotifier.reseller_certificate_order_paid(ssl_account, self).deliver
-
else
-
valid_recipients_list.each do |c|
-
OrderNotifier.certificate_order_paid(c, self).deliver
-
end
-
end
-
site_seal.conditionally_activate!
-
end
-
-
# will cycle through billing profile to purchase certificate order
-
# use the billing profile associated with this order
-
# otherwise, find most recent successfully purchased order and use it's billing profile,
-
# cannot rely on order transactions, since the data was not migrated
-
-
# notify can be "none", "success", or "all"
-
1
def purchase_renewal(notify)
-
bp=order.billing_profile
-
response=[bp, (ssl_account.cached_orders.map(&:billing_profile)-[bp]).shift].compact.each do |bp|
-
p "purchase using billing_profile_id==#{bp.id}"
-
options={profile: bp, cvv: false}
-
new_cert = self.dup
-
new_cert.certificate_contents.build
-
new_cert.duration=1 #only renew 1 year at a time
-
co = Order.setup_certificate_order(certificate: renewal_certificate, certificate_order: new_cert)
-
co.parent = self
-
reorder=ssl_account.purchase co
-
reorder.cents = co.attributes_before_type_cast["amount"].to_f
-
gateway_response=reorder.rebill(options)
-
RenewalAttempt.create(
-
certificate_order_id: self.id, order_transaction_id: gateway_response.id)
-
if gateway_response.success?
-
#self.quantity=1
-
#clone_for_renew([self], reorder)
-
#reorder.line_items.last.sellable.update_attribute :renewal_id, self.id
-
co.save
-
reorder.save
-
if notify=="success"
-
begin
-
logger.info "Sending notification to #{valid_recipients_list.join(",")}"
-
valid_recipients_list.each do |rec|
-
body = OrderNotifier.certificate_order_paid(rec, co, true)
-
body.deliver unless body.to.empty?
-
end
-
RenewalNotification.create(certificate_order_id:
-
co.id, subject: body.subject,
-
body: body, recipients: valid_recipients_list)
-
rescue Exception=>e
-
logger.error e.backtrace.inspect
-
raise e
-
end
-
end
-
return gateway_response
-
else
-
co.destroy
-
end
-
gateway_response
-
end.last
-
end
-
-
#def purchase_using(profile)
-
# credit_card = ActiveMerchant::Billing::CreditCard.new({
-
# :first_name => profile.first_name,
-
# :last_name => profile.last_name,
-
# :number => profile.card_number,
-
# :month => profile.expiration_month,
-
# :year => profile.expiration_year
-
# })
-
# credit_card.type = 'bogus' if defined?(::GATEWAY_TEST_CODE)
-
#end
-
-
1
def clone_for_renew(certificate_orders, order)
-
cached_certificate_orders.each do |cert|
-
cert.quantity.times do |i|
-
#could use cert.dup after >=3.1, but we are currently on 3.0.10 so we'll do this manually
-
new_cert = cert.dup
-
cert.sub_order_items.each {|soi|
-
new_cert.sub_order_items << soi.dup
-
}
-
if cert.migrated_from_v2?
-
pvg = new_cert.sub_order_items[0].
-
product_variant_item.product_variant_group
-
pvg.variantable=cert.renewal_certificate
-
pvg.save
-
end
-
new_cert.line_item_qty = cert.quantity if(i==cert.quantity-1)
-
new_cert.preferred_payment_order = 'prepaid'
-
new_cert.save
-
cc = CertificateContent.new
-
cc.certificate_order=new_cert
-
cc.save
-
order.line_items.build :sellable=>new_cert
-
end
-
end
-
end
-
-
# used for determining which Sub Ca certs to use
-
1
def set_comodo_subca(params, options={})
-
cci=Settings.ca_certificate_id_dv # default is DV
-
if options[:ca_certificate_id]
-
cci = options[:ca_certificate_id]
-
elsif [CA_CERTIFICATES[:SSLcomSHA2]].include? self.ca
-
cci = if external_order_number_meta=="EV"
-
Settings.ca_certificate_id_ev
-
elsif external_order_number_meta=="OV"
-
Settings.ca_certificate_id_ov
-
elsif external_order_number_meta=="DV"
-
Settings.ca_certificate_id_dv
-
else
-
if Settings.send_dv_first
-
Settings.ca_certificate_id_dv #first time needs to be DV
-
else
-
if certificate.is_ev?
-
Settings.ca_certificate_id_ev
-
elsif certificate.is_ov?
-
Settings.ca_certificate_id_ov
-
else
-
Settings.ca_certificate_id_dv
-
end
-
end
-
end
-
elsif certificate.serial=~/256sslcom/
-
cci = if certificate.is_ev?
-
"403"
-
elsif certificate.is_essential_ssl?
-
"401"
-
else
-
"402"
-
end
-
end
-
params.merge!('caCertificateID' => cci.to_s)
-
end
-
-
-
1
def self.trial_conversions(start=30.days.ago, finish=Date.today)
-
free, nonfree, result, stats, count = {}, {}, {}, [], 0
-
CertificateOrder.range(start, finish).not_test.free.map{|co|free.merge!(co.id.to_s => co.all_domains) unless co.all_domains.blank?}
-
CertificateOrder.range(start, finish).not_test.nonfree.map{|co|nonfree.merge!(co.id.to_s => co.all_domains) unless co.all_domains.blank?}
-
nonfree.each do |nk,nv|
-
free.each do |fk,fv|
-
if !(nv & fv).empty?
-
count+=1
-
co_fk = CertificateOrder.find(fk)
-
co_nk = CertificateOrder.find(nk)
-
result.merge!([co_fk.ref, 0.01*co_fk.amount, co_fk.created_at.strftime("%b %d, %Y")]=>
-
[co_nk.ref, 0.01*co_nk.amount, co_nk.created_at.strftime("%b %d, %Y")])
-
stats<<[co_fk.ref, 0.01*co_fk.amount, co_fk.created_at.strftime("%b %d, %Y"),
-
co_nk.ref, 0.01*co_nk.amount, co_nk.created_at.strftime("%b %d, %Y")].join("/")
-
free.delete fk
-
break
-
end
-
end
-
end
-
File.open("/tmp/trial_conversions.txt", "w") { |file| file.write stats.join("\n") }
-
[count,result]
-
end
-
-
# cron job that flags unused certificate_order credits as expired after a period of time (1 year)
-
1
def self.expire_credits(options={})
-
Website.sandbox_db.use_database if options[:db]=="sandbox"
-
CertificateOrder.unflagged_expired_credits.update_all(is_expired: true)
-
SystemAudit.create(owner: nil, target: nil,
-
notes: "",
-
action: "CertificateOrder#expire_credits(#{options.to_s})")
-
end
-
end
-
class CertificateOrderDomain < ActiveRecord::Base
-
belongs_to :certificate_order
-
belongs_to :domain
-
end
-
class CertificateOrderManagedCsr < ActiveRecord::Base
-
belongs_to :certificate_order
-
belongs_to :managed_csr
-
end
-
class CertificateOrderToken < ActiveRecord::Base
-
belongs_to :certificate_order
-
belongs_to :ssl_account
-
belongs_to :user
-
-
PENDING_STATUS = 'pending'
-
EXPIRED_STATUS = 'expired'
-
FAILED_STATUS = 'failed'
-
DONE_STATUS = 'done'
-
PHONE_VERIFICATION_LIMIT_MAX_COUNT = 3
-
PHONE_CALL_LIMIT_MAX_COUNT = 3
-
CALLBACK_SCHEDULE = 'schedule'
-
CALLBACK_MANUAL = 'manual'
-
-
scope :scheduled_callback, -> {
-
where{(status == PENDING_STATUS) &
-
(callback_type == CALLBACK_SCHEDULE) &
-
(is_callback_done == false) &
-
(callback_datetime < DateTime.current())
-
}
-
}
-
end
-
require 'oauth'
-
class ClientApplication < ActiveRecord::Base
-
belongs_to :user
-
has_many :tokens, :class_name => "OauthToken"
-
has_many :access_tokens
-
has_many :oauth2_verifiers
-
has_many :oauth_tokens
-
validates_presence_of :name, :url, :key, :secret
-
validates_uniqueness_of :key
-
before_validation :generate_keys, :on => :create
-
-
validates_format_of :url, :with => /\Ahttp(s?):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/i
-
validates_format_of :support_url, :with => /\Ahttp(s?):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/i, :allow_blank=>true
-
validates_format_of :callback_url, :with => /\Ahttp(s?):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/i, :allow_blank=>true
-
-
attr_accessor :token_callback_url
-
-
def self.find_token(token_key)
-
token = OauthToken.find_by_token(token_key, :include => :client_application)
-
if token && token.authorized?
-
token
-
else
-
nil
-
end
-
end
-
-
def self.verify_request(request, options = {}, &block)
-
begin
-
signature = OAuth::Signature.build(request, options, &block)
-
return false unless OauthNonce.remember(signature.request.nonce, signature.request.timestamp)
-
value = signature.verify
-
value
-
rescue OAuth::Signature::UnknownSignatureMethod => e
-
false
-
end
-
end
-
-
def oauth_server
-
@oauth_server ||= OAuth::Server.new("http://your.site")
-
end
-
-
def credentials
-
@oauth_client ||= OAuth::Consumer.new(key, secret)
-
end
-
-
# If your application requires passing in extra parameters handle it here
-
def create_request_token(params={})
-
RequestToken.create :client_application => self, :callback_url=>self.token_callback_url
-
end
-
-
protected
-
-
def generate_keys
-
self.key = OAuth::Helper.generate_key(40)[0,40]
-
self.secret = OAuth::Helper.generate_key(40)[0,40]
-
end
-
end
-
require 'net/http'
-
require 'net/https'
-
require 'open-uri'
-
-
class ComodoApi
-
CREDENTIALS={
-
'loginName' => Rails.application.secrets.comodo_api_username,
-
'loginPassword' => Rails.application.secrets.comodo_api_password
-
}
-
-
CODE_SIGNING_PRODUCT={"1"=>"x_PPP=1511", "2"=>"x_PPP=1512", "3"=>"x_PPP=1509"}
-
SIGNATURE_HASH = %w(NO_PREFERENCE INFER_FROM_CSR PREFER_SHA2 PREFER_SHA1 REQUIRE_SHA2)
-
REPLACE_SSL_URL="https://secure.trust-provider.com/products/!AutoReplaceSSL"
-
APPLY_SSL_URL="https://secure.trust-provider.com/products/!AutoApplySSL"
-
PLACE_ORDER_URL="https://secure.trust-provider.com/products/!PlaceOrder"
-
RESEND_DCV_URL="https://secure.trust-provider.com/products/!ResendDCVEmail"
-
AUTO_UPDATE_URL="https://secure.trust-provider.com/products/!AutoUpdateDCV"
-
AUTO_REMOVE_URL="https://secure.trust-provider.com/products/!AutoRemoveMDCDomain"
-
REVOKE_SSL_URL="https://secure.trust-provider.com/products/!AutoRevokeSSL"
-
COLLECT_SSL_URL="https://secure.trust-provider.com/products/download/CollectSSL"
-
GET_MDC_DETAILS="https://secure.trust-provider.com/products/!GetMDCDomainDetails"
-
RESPONSE_TYPE={"zip"=>0,"netscape"=>1, "pkcs7"=>2, "individually"=>3}
-
RESPONSE_ENCODING={"base64"=>0,"binary"=>1}
-
-
def self.auto_replace_ssl(options={})
-
cc = options[:certificate_order].certificate_content
-
last_unique_value = cc.csr.csr_unique_values.create(unique_value: SecureRandom.hex(5))
-
options[:send_to_ca]=true unless options[:send_to_ca]==false
-
comodo_params = {
-
'orderNumber'=>options[:certificate_order].external_order_number,
-
'domainNames'=>options[:domainNames],
-
# 'dcvEmailAddresses'=>options[:domainDcvs],
-
'isCustomerValidated'=>'N',
-
'uniqueValue' => last_unique_value.unique_value
-
}
-
comodo_params = comodo_params.merge(CREDENTIALS).map{|k,v|"#{k}=#{v}"}.join("&")
-
-
host = REPLACE_SSL_URL
-
url = URI.parse(host)
-
con = Net::HTTP.new(url.host, 443)
-
con.verify_mode = OpenSSL::SSL::VERIFY_PEER
-
con.ca_path = '/etc/ssl/certs' if File.exists?('/etc/ssl/certs') # Ubuntu
-
con.use_ssl = true
-
cc.csr.touch
-
res = unless [false,"false"].include? options[:send_to_ca]
-
con.start do |http|
-
http.request_post(url.path, comodo_params)
-
end
-
end
-
ccr=cc.csr.ca_certificate_requests.create(request_url: host,
-
parameters: comodo_params, method: "post", response: res.try(:body), ca: "comodo")
-
-
unless ccr.success?
-
OrderNotifier.problem_ca_sending("comodo@ssl.com", options[:certificate_order],"comodo").deliver
-
else
-
options[:certificate_order].update_column(:external_order_number, ccr.order_number) if ccr.order_number
-
end
-
res.try(:body)
-
end
-
-
def self.apply_for_certificate(certificate_order, options={})
-
cc = options[:certificate_content] || certificate_order.certificate_content
-
comodo_options = certificate_order.options_for_ca(options).
-
merge(CREDENTIALS).map{|k,v|"#{k}=#{v}"}.join("&")
-
# reprocess or new
-
host = comodo_options["orderNumber"] ? REPLACE_SSL_URL : APPLY_SSL_URL
-
url = URI.parse(host)
-
con = Net::HTTP.new(url.host, 443)
-
con.verify_mode = OpenSSL::SSL::VERIFY_PEER
-
con.ca_path = '/etc/ssl/certs' if File.exists?('/etc/ssl/certs') # Ubuntu
-
con.use_ssl = true
-
cc.csr.touch
-
res = unless [false,"false"].include? options[:send_to_ca]
-
con.start do |http|
-
http.request_post(url.path, comodo_options)
-
end
-
end
-
ccr=cc.csr.ca_certificate_requests.create(request_url: host,
-
parameters: comodo_options, method: "post", response: res.try(:body), ca: "comodo")
-
unless ccr.success?
-
OrderNotifier.problem_ca_sending("comodo@ssl.com", certificate_order,"comodo").deliver
-
else
-
certificate_order.update_column(:external_order_number, ccr.order_number) if ccr.order_number
-
end
-
ccr
-
end
-
-
def self.domain_control_email_choices(obj_or_domain)
-
is_a_obj = (obj_or_domain.is_a?(Csr) or obj_or_domain.is_a?(CertificateName)) ? true : false
-
comodo_options = {'domainName' => is_a_obj ? obj_or_domain.try(:common_name) : obj_or_domain}.
-
merge(CREDENTIALS).map{|k,v|"#{k}=#{v}"}.join("&")
-
host = "https://secure.trust-provider.com/products/!GetDCVEmailAddressList"
-
res = send_comodo(host, comodo_options)
-
attr = {request_url: host,
-
parameters: comodo_options, method: "post", response: res.body, ca: "comodo"}
-
if is_a_obj
-
dcv=obj_or_domain.ca_dcv_requests.create(attr)
-
obj_or_domain.domain_control_validations.create(
-
candidate_addresses: dcv.email_address_choices, subject: dcv.domain_name)
-
dcv
-
else
-
CaDcvRequest.new(attr)
-
end
-
end
-
-
def self.resend_dcv(options)
-
owner = options[:dcv].csr || options[:dcv].certificate_name
-
comodo_options = {'dcvEmailAddress' => options[:dcv].email_address,
-
'orderNumber'=> owner.certificate_content.certificate_order.external_order_number}.
-
merge(CREDENTIALS).map{|k,v|"#{k}=#{v}"}.join("&")
-
host = RESEND_DCV_URL
-
res = send_comodo(host, comodo_options)
-
attr = {request_url: host,
-
parameters: comodo_options, method: "post", response: res.body, ca: "comodo", api_requestable: owner}
-
CaDcvResendRequest.create(attr)
-
end
-
-
def self.auto_remove_domain(options={})
-
owner = options[:domain_name]
-
comodo_options = {'orderNumber'=>options[:order_number].to_i, 'domainName'=>owner.name}
-
comodo_options = comodo_options.merge!(CREDENTIALS).map{|k,v|"#{k}=#{v}"}.join("&")
-
-
host = AUTO_REMOVE_URL
-
res = send_comodo(host, comodo_options)
-
-
attr = {
-
request_url: host,
-
parameters: comodo_options,
-
method: "post",
-
response: res.body,
-
ca: "comodo",
-
api_requestable: owner
-
}
-
-
CaDcvResendRequest.create(attr)
-
res.body
-
end
-
-
# this is the only way to update multi domain dcv after the order is submitted
-
def self.auto_update_dcv(options={})
-
options[:send_to_ca] = true unless options[:send_to_ca] == false
-
-
if options[:dcv].certificate_name #assume ucc
-
owner = options[:dcv].certificate_name
-
order_number = owner.certificate_content.certificate_order.external_order_number
-
is_ucc = owner.certificate_content.certificate_order.certificate.is_ucc?
-
domain_name = owner.name
-
dcv_method = owner.last_dcv_for_comodo_auto_update_dcv
-
else #assume single domain
-
owner = options[:dcv]
-
order_number = owner.csr.certificate_content.certificate_order.external_order_number
-
is_ucc = owner.csr.certificate_content.certificate_order.certificate.is_ucc?
-
domain_name = owner.csr.common_name
-
dcv_method = CertificateName.to_comodo_method(owner.dcv_method)
-
end
-
comodo_options = {'orderNumber'=> order_number,
-
'newMethod'=>dcv_method}
-
comodo_options.merge!('domainName'=>domain_name) if (is_ucc) #domain is no necessary for single name certs
-
comodo_options.merge!('newDCVEmailAddress' => options[:dcv].email_address) if (options[:dcv].dcv_method=="email")
-
comodo_options = comodo_options.merge!(CREDENTIALS).map{|k,v|"#{k}=#{v}"}.join("&")
-
-
if options[:send_to_ca] && order_number
-
host = AUTO_UPDATE_URL
-
res = send_comodo(host, comodo_options)
-
attr = {request_url: host,
-
parameters: comodo_options, method: "post", response: res.body, ca: "comodo", api_requestable: owner}
-
CaDcvResendRequest.create(attr)
-
else
-
comodo_options
-
end
-
end
-
-
def self.send_comodo(host, options={})
-
url = URI.parse(host)
-
con = Net::HTTP.new(url.host, 443)
-
con.verify_mode = OpenSSL::SSL::VERIFY_PEER
-
con.ca_path = '/etc/ssl/certs' if File.exists?('/etc/ssl/certs') # Ubuntu
-
con.use_ssl = true
-
res = con.start do |http|
-
http.request_post(url.path, options)
-
end
-
end
-
-
def self.collect_ssl(certificate_order, options={})
-
comodo_options = params_collect(certificate_order, options)
-
host = COLLECT_SSL_URL
-
res = send_comodo(host, comodo_options)
-
attr = {request_url: host,
-
parameters: comodo_options, method: "post", response: res.body, ca: "comodo", api_requestable: certificate_order}
-
CaRetrieveCertificate.create(attr)
-
end
-
-
def self.revoke_ssl(options={})
-
comodo_options = params_revoke(options)
-
host = REVOKE_SSL_URL
-
res = send_comodo(host, comodo_options)
-
attr = {request_url: host, parameters: comodo_options, method: "post", response: res.body, ca: "comodo",
-
api_requestable: options[:certificate_order] || options[:api_requestable]}
-
CaRevokeCertificate.create(attr)
-
end
-
-
def self.apply_apac(certificate_order,options={})
-
certificate = certificate_order.certificate
-
registrant=certificate_order.certificate_content.registrant
-
comodo_options = { # basic
-
'ap' => 'SecureSocketsLaboratories',
-
"reseller" => "Y",
-
"1_PPP"=> ppp_parameter(certificate_order),
-
"emailAddress"=>certificate_order.csr.common_name,
-
"loginName"=>certificate_order.ref,
-
"loginPassword"=>certificate_order.order.reference_number,
-
"1_csr"=>certificate_order.csr.body,
-
"caCertificateID"=> Settings.ca_certificate_id_client,
-
"1_signatureHash"=>"PREFER_SHA2"}
-
comodo_options.merge!( # pro
-
"forename"=>registrant.first_name,
-
"surname"=>registrant.last_name) unless certificate.product_root=~/basic/i
-
comodo_options.merge!( # business
-
"title"=>registrant.title,
-
"organizationName"=>registrant.company_name,
-
"postOfficeBox"=>registrant.po_box,
-
"streetAddress1"=>registrant.address1,
-
"streetAddress2"=>registrant.address2,
-
"streetAddress3"=>registrant.address3,
-
"localityName"=>registrant.city,
-
"stateOrProvinceName"=>registrant.state,
-
"postalCode"=>registrant.postal_code,
-
"country"=>registrant.country,
-
"telephoneNumber"=>registrant.phone,
-
'orderNumber' => (options[:external_order_number] || certificate_order.external_order_number)) if
-
certificate.product_root=~/enterprise\z/i || certificate.product_root=~/business\z/i
-
comodo_options.merge!( # enterprise
-
"organizationalUnitName"=>registrant.department) if certificate.product_root=~/enterprise\z/i
-
comodo_options=comodo_options.map { |k, v| "#{k}=#{CGI::escape(v) if v}" }.join("&")
-
if options[:send_to_ca]
-
host = PLACE_ORDER_URL
-
res = send_comodo(host, comodo_options)
-
attr = {request_url: host,
-
parameters: comodo_options, method: "post", response: res.body, ca: "comodo", api_requestable: certificate_order}
-
CaCertificateRequest.create(attr)
-
else
-
comodo_options
-
end
-
# "title forename surname emailAddress x_PPP x_csr"
-
# "title forename surname emailAddress organizationName organizationalUnitName streetAddress1 streetAddress2 streetAddress3 x_PPP x_csr localityName stateOrProvinceName postalCode countryName "
-
end
-
-
def self.apply_code_signing(certificate_order,options={}.reverse_merge!(send_to_ca: true))
-
registrant=certificate_order.certificate_content.registrant
-
comodo_options = {
-
"loginName"=>certificate_order.ref,
-
"loginPassword"=>certificate_order.order.reference_number,
-
"emailAddress"=>registrant.email,
-
'ap' => 'SecureSocketsLaboratories',
-
"reseller" => "Y",
-
"1_contactEmailAddress"=>registrant.email,
-
"organizationName"=>registrant.company_name,
-
"organizationalUnitName"=>registrant.department,
-
"postOfficeBox"=>registrant.po_box,
-
"streetAddress1"=>registrant.address1,
-
"streetAddress2"=>registrant.address2,
-
"streetAddress3"=>registrant.address3,
-
"localityName"=>registrant.city,
-
"stateOrProvinceName"=>registrant.state,
-
"postalCode"=>registrant.postal_code,
-
"country"=>registrant.country,
-
"dunsNumber"=>"",
-
"companyNumber"=>"",
-
"1_csr"=>certificate_order.csr.body,
-
"caCertificateID"=>Settings.ca_certificate_id_code_signing,
-
"1_signatureHash"=>"PREFER_SHA2",
-
"1_PPP"=> ppp_parameter(certificate_order),
-
'orderNumber' => (options[:external_order_number] || certificate_order.external_order_number)}
-
comodo_options=comodo_options.map { |k, v| "#{k}=#{CGI::escape(v) if v}" }.join("&")
-
if options[:send_to_ca]
-
host = PLACE_ORDER_URL
-
res = send_comodo(host, comodo_options)
-
attr = {request_url: host,
-
parameters: comodo_options, method: "post", response: res.body, ca: "comodo", api_requestable: certificate_order}
-
CaCertificateRequest.create(attr)
-
else
-
comodo_options
-
end
-
end
-
-
# mdc = multi domain certificate
-
def self.mdc_status(certificate_order)
-
comodo_options = params_domains_status(certificate_order)
-
host = GET_MDC_DETAILS
-
res = send_comodo(host, comodo_options)
-
attr = {request_url: host,
-
parameters: comodo_options, method: "post", response: res.body, ca: "comodo", api_requestable: certificate_order}
-
CaMdcStatus.create(attr)
-
end
-
-
def self.params_collect(certificate_order, options={})
-
comodo_params = {'queryType' => 2, "showExtStatus" => "Y",
-
'baseOrderNumber' => certificate_order.external_order_number}
-
comodo_params.merge!("queryType" => 1, "responseType" => RESPONSE_TYPE[options[:response_type]]) if options[:response_type]
-
comodo_params.merge!("queryType" => 1, "responseType" => RESPONSE_TYPE[options[:response_type]],
-
"responseEncoding" => RESPONSE_ENCODING[options[:response_encoding]].to_i) if ["zip", "pkcs7"].include?(options[:response_type]) &&
-
options[:response_encoding]=="binary"
-
# comodo_params.merge!("showMDCDomainDetail"=>"Y", "showMDCDomainDetail2"=>"Y") if certificate_order.certificate.is_ucc?
-
comodo_params.merge(CREDENTIALS).map { |k, v| "#{k}=#{v}" }.join("&")
-
end
-
-
def self.params_domains_status(certificate_order)
-
comodo_params = {'showStatusDetails' => "Y", 'orderNumber' => certificate_order.external_order_number}
-
comodo_params.merge(CREDENTIALS).map { |k, v| "#{k}=#{v}" }.join("&")
-
end
-
-
def self.params_revoke(options)
-
target = if options[:serial]
-
{'serialNumber' => options[:serial].upcase}
-
else
-
{'orderNumber' => options[:external_order_number] || options[:certificate_order].external_order_number}
-
end
-
comodo_params = {'revocationReason' => options[:refund_reason]}.merge(target)
-
comodo_params.merge(CREDENTIALS).map { |k, v| "#{k}=#{v}" }.join("&")
-
end
-
-
def self.ppp_parameter(certificate_order)
-
certificate = certificate_order.certificate
-
if certificate.is_code_signing?
-
case certificate_order.certificate_duration(:years)
-
when "1"
-
"1511"
-
when "2"
-
"1512"
-
when "3"
-
"1509"
-
end
-
elsif certificate.is_client?
-
if certificate.is_client_basic?
-
case certificate_order.certificate_duration(:years)
-
when "1"
-
"5029"
-
when "2"
-
"5030"
-
when "3"
-
"5031"
-
end
-
elsif certificate.is_client_pro?
-
case certificate_order.certificate_duration(:years)
-
when "1"
-
"5032"
-
when "2"
-
"5033"
-
when "3"
-
"5034"
-
end
-
elsif certificate.is_client_business? || certificate.is_client_enterprise?
-
case certificate_order.certificate_duration(:years)
-
when "1"
-
"5035"
-
when "2"
-
"5036"
-
when "3"
-
"5037"
-
end
-
end
-
end
-
end
-
-
# def self.test
-
# ssl_util = Savon::Client.new "http://ccm-host/ws/EPKIManagerSSL?wsdl"
-
# begin
-
# response = ssl_util.enroll do |soap|
-
# soap.body = {:csr => csr}
-
# end
-
# rescue
-
-
# client = Savon::Client.new do |wsdl, http|
-
# wsdl.document = "http://ccm-host/ws/EPKIManagerSSL?wsdl"
-
# end
-
# client.wsdl.soap_actions
-
# end
-
end
-
-
module Encodable
-
extend ActiveSupport::Concern
-
-
TARGET_ENCODING = Encoding.find("UTF-8") # #<Encoding:UTF-8>
-
TARGET_ENCODING_NAME = Encoding.find("UTF-8").to_s # 'UTF-8'
-
-
# Returns encoded string of the passed string
-
def force_string_encoding(str)
-
if str.is_a?(String) && str.respond_to?(:force_encoding)
-
str = str.dup if str.frozen?
-
str.force_encoding(TARGET_ENCODING) if Encoding.compatible?(str.encoding.name, TARGET_ENCODING_NAME)
-
str.encode!(TARGET_ENCODING, 'binary', invalid: :replace, undef: :replace, replace: '')
-
end
-
str
-
end
-
end
-
1
module Filterable
-
1
extend ActiveSupport::Concern
-
-
COMPARISON = {
-
1
less_than: '<',
-
greater_than: '>',
-
equal: '=',
-
less_or_equal: '<=',
-
greater_or_equal: '>='
-
}
-
-
1
class_methods do
-
1
def filter(filters = nil, scope = nil, relationship = nil)
-
self.filter_scope = scope || where(nil)
-
return filter_scope if filters.blank?
-
-
filters.each_pair do |filter_attr, operation_hash|
-
if is_relationship?(filter_attr)
-
# TODO: Check if this is performant. Possible n + 1
-
self.filter_scope = filter_scope.references(filter_attr)
-
# TODO: Have a recursion check to make sure that this method in not
-
# infinite looping
-
filter(operation_hash, filter_scope, filter_attr)
-
else
-
operation(filter_attr, operation_hash, relationship)
-
end
-
end
-
-
filter_scope
-
end
-
-
1
def operation(filter_attr, operation_hash, relationship)
-
operation_hash.each_pair do |operator, value|
-
raise "NOPE!" unless valid_operator? operator
-
-
self.filter_scope = filter_scope.where(
-
where_sql(filter_attr, operator, value, relationship)
-
)
-
end
-
end
-
-
1
def where_sql(filter_attr, operator, value, relationship)
-
if relationship
-
"#{relationship.to_s.pluralize}.#{filter_attr} #{operator} #{format_sql_value(value)}"
-
elsif filter_attr == :created_at
-
"DATE(#{table_name}.#{filter_attr}) #{operator} #{format_sql_value(value)}"
-
elsif operator == 'LIKE'
-
if filter_attr.to_s.include?('roles')
-
# search in serialized array
-
["lower(#{table_name}.roles) #{operator} (?)", "% #{value}\n%"]
-
else
-
["lower(#{table_name}.#{filter_attr}) #{operator} (?)", "%#{value.downcase}%"]
-
end
-
else
-
"#{table_name}.#{filter_attr} #{operator} #{format_sql_value(value)}"
-
end
-
end
-
-
1
def format_sql_value(value)
-
if value.is_a? Array
-
value.to_s.gsub("[", "(").gsub("]", ")").gsub('"', "'")
-
else
-
"'#{value}'"
-
end
-
end
-
-
1
def valid_operator?(operator)
-
['<', '>', '<=', '>=', '=', '!=', 'in', 'not in', 'LIKE'].include?(operator)
-
end
-
-
1
def is_relationship?(filter_attr)
-
reflections.keys.include? filter_attr.to_s
-
end
-
-
1
def filter_scope
-
instance_variable_get(:@filter_scope)
-
end
-
-
1
def filter_scope=(scope)
-
instance_variable_set(:@filter_scope, scope)
-
end
-
end
-
end
-
module ModelCachingExtension
-
extend ActiveSupport::Concern
-
-
included do
-
class << self
-
# The first time you call Model.all_cached it will cache the collection,
-
# each consequent call will not fire the DB query
-
def all_cached
-
Rails.cache.fetch(["cached_#{name.underscore.to_s}s"]) { self.all.entries }
-
end
-
end
-
-
after_commit :clear_cache
-
-
private
-
-
# Making sure, that data is in consistent state by removing the cache
-
# everytime, the table is touched (eg some record is edited/created/destroyed etc).
-
def clear_cache
-
Rails.cache.delete(["cached_#{name.underscore.to_s}"])
-
end
-
end
-
end
-
module SmimeClientEnrollable
-
extend ActiveSupport::Concern
-
-
def smime_client_enroll_recipients(current_user_id)
-
@sce_ssl = billable
-
@sce_current_user = User.find current_user_id
-
@sce_epki_registrant = @sce_ssl.epki_registrant
-
-
certificate_orders.includes(:certificate_contents).uniq.each do |co|
-
@sce_co = co
-
@sce_email = @sce_co.certificate_content.domains.first
-
@sce_iv_exists = @sce_ssl.individual_validations.find_by(email: @sce_email)
-
-
if @sce_iv_exists && User.find_by(id: @sce_iv_exists.user_id)
-
@sce_co.update_column(:assignee_id, @sce_iv_exists.user_id)
-
else
-
smime_client_enroll_invite_recipient
-
end
-
-
if @sce_iv_exists && @sce_iv_exists.persisted?
-
LockedRecipient.create_for_co(@sce_co, @sce_iv_exists.user_id)
-
smime_client_enroll_validate
-
end
-
end
-
end
-
-
def smime_client_enroll_invite_recipient
-
user_exists = User.find_by(email: @sce_email)
-
if user_exists
-
user_exists_for_team = @sce_ssl.users.find_by(id: user_exists.id)
-
-
if user_exists_for_team
-
@sce_iv_exists = @sce_ssl.individual_validations.find_by(email: user_exists_for_team.email)
-
smime_client_enroll_sync_user_iv(user_exists_for_team.id)
-
end
-
-
unless @sce_iv_exists
-
# Add IV for user to team.
-
@sce_iv_exists = @sce_ssl.individual_validations.create(
-
first_name: (user_exists.first_name || ''),
-
last_name: (user_exists.last_name || ''),
-
email: user_exists.email,
-
status: user_exists_for_team ? Contact::statuses[:validated] : Contact::statuses[:in_progress],
-
user_id: user_exists.id
-
)
-
end
-
-
# Add user to team w/role individual_certificate
-
unless user_exists_for_team
-
user_exists.ssl_accounts << @sce_ssl
-
user_exists.set_roles_for_account(
-
@sce_ssl, [Role::get_individual_certificate_id]
-
)
-
end
-
-
@sce_co.update_column(:assignee_id, user_exists.id)
-
else
-
smime_client_enroll_invite_new_recipient
-
end
-
end
-
-
def smime_client_enroll_invite_new_recipient
-
new_user = @sce_current_user.invite_new_user(
-
{ user: {email: @sce_email, first_name: '', last_name: ''} }
-
)
-
if new_user.persisted?
-
smime_client_enroll_invite_recipient
-
end
-
end
-
-
def smime_client_enroll_sync_user_iv(user_id)
-
unless user_id == @sce_iv_exists.user_id
-
@sce_iv_exists.update_column(:user_id, user_id)
-
end
-
end
-
-
def smime_client_enroll_validate
-
require_ov_iv = @sce_co.certificate.requires_locked_registrant?
-
ov = @sce_co.locked_registrant
-
lr = @sce_co.locked_recipient
-
cc = @sce_co.certificate_content
-
-
if @sce_epki_registrant.applies_to_certificate_order?(@sce_co)
-
ov.validated! if require_ov_iv && !ov.validated?
-
lr.validated! unless lr.validated?
-
@sce_iv_exists.validated! unless @sce_iv_exists.validated?
-
cc.validate! unless cc.validated?
-
else
-
ov.pending_validation! if require_ov_iv && !ov.pending_validation?
-
lr.pending_validation! unless lr.pending_validation?
-
@sce_iv_exists.pending_validation! unless @sce_iv_exists.pending_validation?
-
cc.pend_validation! unless cc.pending_validation?
-
end
-
end
-
end
-
module Sortable
-
extend ActiveSupport::Concern
-
-
module ClassMethods
-
def sort_with(params)
-
column_name = params[:column]
-
direction = params[:direction]
-
-
scope = order(created_at: :desc) if column_name.blank? || direction.blank?
-
if (column_name && direction) &&
-
(valid_request?(column_name, direction) || valid_association?(column_name))
-
scope = scope_by_column_name(column_name.to_sym, direction.to_sym)
-
end
-
scope
-
end
-
-
private
-
-
def scope_by_column_name(column_name, direction)
-
case column_name
-
when :end_date
-
order("invoices.end_date #{direction.upcase}")
-
when :start_date
-
order("invoices.start_date #{direction.upcase}")
-
when :reference_number
-
order("invoices.reference_number #{direction.upcase}")
-
when :status
-
order("invoices.status #{direction.upcase}")
-
when :orders
-
group("orders.invoice_id").order!("count(orders.invoice_id) #{direction.upcase}")
-
else
-
order(Hash[column_name, direction])
-
end
-
end
-
-
def valid_association?(column_name)
-
method_defined?(column_name.to_sym)
-
end
-
-
def valid_request?(column_name, direction)
-
column_valid?(column_name) && direction_valid?(direction)
-
end
-
-
def column_valid?(column_name)
-
column_names.include?(column_name)
-
end
-
-
def direction_valid?(direction)
-
%i[desc asc].include?(direction.to_sym)
-
end
-
end
-
end
-
module Stripeable
-
extend ActiveSupport::Concern
-
-
class_methods do
-
def stripe_purchase(amount, credit_card, options = {})
-
card_token = options[:stripe_card_token]
-
@ot = OrderTransaction.new
-
@ot.action = 'purchase'
-
@ot.amount = amount.to_s
-
card_token = @ot.create_card_token(credit_card, options) unless card_token
-
@ot.create_charge(amount, card_token, options)
-
@ot
-
end
-
end
-
-
def create_charge(amount, card_token, options = {})
-
begin
-
charge = stripe_charge(amount, card_token, options)
-
rescue => e
-
log_failure(e, card_token)
-
else
-
log_charge_response(charge)
-
end
-
end
-
-
def stripe_charge(amount, card_token, options = {})
-
description = options[:description]
-
Stripe::Charge.create(
-
source: card_token,
-
amount: amount.cents,
-
description: description,
-
statement_descriptor: description[0..21], # can only be 22 chars long
-
currency: 'usd',
-
receipt_email: 'sales@ssl.com' #options[:owner_email]
-
)
-
end
-
# Ceate Stripe card token if using an existing CC billing profile for purchase
-
def create_card_token(credit_card, options = {})
-
address = options[:billing_address]
-
token = nil
-
begin
-
token = Stripe::Token.create(
-
card: {
-
name: "#{credit_card.first_name} #{credit_card.last_name}",
-
number: credit_card.number,
-
exp_month: credit_card.month,
-
exp_year: credit_card.year,
-
cvc: credit_card.verification_value,
-
address_line1: address[:street1],
-
address_city: address[:locality],
-
address_state: address[:region],
-
address_zip: address[:postal_code]
-
},
-
)
-
rescue => e
-
log_failure(e, token)
-
else
-
token
-
end
-
end
-
-
def log_charge_response(charge)
-
self.reference = charge[:id]
-
self.success = charge[:status] == 'succeeded' && charge[:paid]
-
self.message = 'This transaction has been approved'
-
self.params = log_charge_response_params(charge)
-
self.test = stripe_test?(charge)
-
self.cvv = charge[:source][:cvc_check]
-
end
-
-
def log_charge_response_params(charge)
-
{
-
merchant: 'Stripe',
-
stripe_charge_id: charge[:id],
-
paid: charge[:paid],
-
outcome: charge[:outcome].to_h,
-
balance_transaction: charge[:balance_transaction],
-
created: charge[:created],
-
card_id: charge[:source].id,
-
account_number: charge[:source][:last4],
-
card_amount: charge[:amount],
-
card_fingerprint: charge[:source].fingerprint
-
}
-
end
-
-
def log_failure(e, card_token=nil)
-
message = if e.class == Stripe::CardError
-
"This transaction has been declined. #{e.message}"
-
else
-
'Something went wrong! The card was not charged.'
-
end
-
self.success = false
-
self.reference = nil
-
self.message = message
-
self.params = log_failure_error(e)
-
self.test = stripe_test?(card_token)
-
end
-
-
def log_failure_error(e)
-
err = e.json_body[:error]
-
{
-
status: e.http_status,
-
type: err[:type],
-
charge_id: err[:charge],
-
code: err[:code],
-
decline_code: err[:decline_code],
-
param: err[:param],
-
message: err[:message],
-
message_more: "#{e.class.to_s} - #{err[:code]}, #{err[:message]}"
-
}
-
end
-
-
def stripe_test?(stripe_object)
-
return false if stripe_object.blank?
-
stripe_object = Stripe::Token.retrieve(stripe_object) if stripe_object.is_a?(String)
-
!stripe_object[:livemode]
-
end
-
end
-
1
module UserMessageable
-
1
extend ActiveSupport::Concern
-
-
1
class_methods do
-
-
end
-
-
1
def mailboxer_name
-
str = "#{self.first_name} #{self.last_name}"
-
str = self.email if str.strip.empty?
-
str
-
end
-
-
1
def mailboxer_email(object)
-
self.email
-
end
-
-
1
def mailboxer_recipients
-
list = get_all_approved_accounts
-
result = []
-
if list.any?
-
result = User.joins(:ssl_account_users)
-
.where(ssl_account_users: {ssl_account_id: list.map(&:id)})
-
.uniq.map{|u| u.email}
-
end
-
result
-
end
-
-
1
def mailboxer_fetch_recipients(conversation)
-
conversation.receipts.reject{ |p| p.receiver == self }
-
.first.receiver.try(:email)
-
end
-
end
-
1
class Contact < ActiveRecord::Base
-
1
include V2MigrationProgressAddon
-
1
include Filterable
-
1
include Workflow
-
# include RefParam
-
-
1
enum status: {
-
in_progress: 1,
-
pending_validation: 5,
-
additional_info: 15,
-
validated: 20,
-
epki_agreement: 25,
-
pending_epki: 30
-
}
-
-
1
belongs_to :contactable, polymorphic: true
-
1
has_many :order_contacts, foreign_key: :parent_id, class_name: 'Contact'
-
1
has_many :notification_groups_subjects, as: :subjectable
-
1
has_many :notification_groups, through: :notification_groups_subjects
-
1
has_many :contact_validation_histories, dependent: :destroy
-
1
has_many :validation_histories, through: :contact_validation_histories
-
1
belongs_to :parent, class_name: "Contact"
-
-
1
attr_accessor :update_parent, :administrative_role, :billing_role, :technical_role, :validation_role, :epki_agreement_request
-
-
1
serialize :special_fields
-
1
serialize :domains
-
-
1
ALIAS_FIELDS = {organization: :company_name, organization_unit: :department,
-
street_address_1: :address1, street_address_2: :address2,
-
street_address_3: :address3, locality: :city, state_or_province: :state, post_office_box: :po_box}
-
1
EXCLUDED_FIELDS = %w(id roles type contactable_id contactable_type created_at updated_at notes)
-
1
EXCLUDED_SAVED = %w(id roles contactable_id contactable_type notes)
-
1
SYNC_FIELDS_REQUIRED = [
-
:title, :first_name, :last_name, :company_name, :department, :po_box,
-
:address1, :address2, :address3, :city, :state, :country, :postal_code,
-
:email, :phone, :ext, :fax
-
]
-
1
SYNC_FIELDS = SYNC_FIELDS_REQUIRED.dup.push(:roles)
-
1
ROLES = %w(administrative billing technical validation)
-
-
1
before_validation :set_roles
-
-
1
workflow do
-
1
state :new do
-
1
event :provide_info, :transitions_to => :info_provided
-
1
event :cancel, :transitions_to => :canceled
-
1
event :issue, :transitions_to => :issued
-
1
event :reset, :transitions_to => :new
-
1
event :validate, :transitions_to => :validated
-
1
event :pend_validation, :transitions_to => :pending_validation
-
end
-
-
1
state :pending_validation do
-
1
event :validate, :transitions_to => :validated
-
1
event :reject, :transitions_to => :rejected
-
1
event :refund, :transitions_to => :refunded
-
1
event :charge_back, :transitions_to => :charged_back
-
end
-
-
1
state :pending_callback do
-
1
event :callback, :transitions_to => :callback_satisfied
-
1
event :validate, :transitions_to => :validated
-
1
event :pend_validation, :transitions_to => :pending_validation
-
1
event :reject, :transitions_to => :rejected
-
end
-
-
1
state :callback_satisfied do
-
end
-
end
-
-
1
ALIAS_FIELDS.each do |k,v|
-
8
alias_attribute k, v
-
end
-
-
1
SyncChildContactsJob = Struct.new(:contact_id) do
-
1
def perform
-
parent = Contact.find contact_id
-
if parent
-
parent.order_contacts.each do |contact|
-
contact.update_attributes(
-
parent.attributes.keep_if {|k,_| Contact::SYNC_FIELDS.include? k.to_sym}
-
)
-
end
-
end
-
end
-
end
-
-
1
def self.get_company_fields
-
[
-
'company_name',
-
'department',
-
'company_number',
-
'incorporation_date',
-
'incorporation_country',
-
'incorporation_state',
-
'incorporation_city',
-
'assumed_name',
-
'business_category',
-
'duns_number',
-
'registration_service',
-
'special_fields'
-
]
-
end
-
# Remove duplicate certificate contacts for current certificate content
-
# of passed certificate order.
-
# Param certificate_order: object, object.id, array of objects, array of ids
-
1
def self.clear_duplicate_co_contacts(certificate_order)
-
co = case certificate_order.class.to_s
-
when 'Integer'
-
[CertificateOrder.find(certificate_order)]
-
when 'Array'
-
certificate_order.map {|o| o.is_a? Integer ? CertificateOrder.find(o) : o}
-
when 'CertificateOrder'
-
[certificate_order]
-
end
-
-
co.each do |cur_co|
-
co_contacts = cur_co.certificate_content.certificate_contacts
-
co_contacts.each do |c|
-
check_attr = c.attributes.keep_if {|k,_| Contact::SYNC_FIELDS_REQUIRED.include?(k.to_sym)}
-
c.destroy if co_contacts.where(check_attr).where.not(id: c.id).any?
-
end
-
end
-
end
-
-
1
def self.index_filter(params)
-
filters = {}
-
p = params
-
filter_roles = p[:roles]
-
filters[:status] = { 'in' => p[:status].map{|s| statuses[s]} } unless p[:status].blank?
-
filters[:first_name] = { 'LIKE' => p[:first_name] } unless p[:first_name].blank?
-
filters[:last_name] = { 'LIKE' => p[:last_name] } unless p[:last_name].blank?
-
filters[:email] = { 'LIKE' => p[:email] } unless p[:email].blank?
-
filters[:company_name] = { 'LIKE' => p[:company_name] } unless p[:company_name].blank?
-
filters[:phone] = { 'LIKE' => p[:phone] } unless p[:phone].blank?
-
-
if filter_roles && filter_roles.any?
-
filter_roles.each_with_index do |role, i|
-
filters["roles_#{i}".to_sym] = { 'LIKE' => role }
-
end
-
end
-
t = p[:team]
-
if t.present?
-
found = SslAccount.where(
-
"ssl_slug = ? OR acct_number = ? OR id = ? OR LOWER(company_name) LIKE LOWER(?)", t, t, t, "%#{t}%"
-
)
-
filters[:contactable_id] = { '=' => found.first.id } if found.any?
-
end
-
result = filter(filters)
-
result
-
end
-
-
1
def contact_iv?
-
type == 'IndividualValidation' && contactable_type == 'SslAccount'
-
end
-
-
1
def contact_ov?
-
type == 'Registrant' && contactable_type == 'SslAccount'
-
end
-
-
1
def get_address_format
-
"#{address1}, #{city}, #{state} #{postal_code}, #{country}"
-
end
-
-
1
def to_api_query
-
{}.tap do |result|
-
(ALIAS_FIELDS.keys+%w(postal_code country email)).each do |k,v|
-
result.merge!(k=>self.send(k))
-
end
-
end
-
# attributes.except(*EXCLUDED_FIELDS)
-
end
-
-
1
def set_roles
-
set_roles = []
-
set_roles << 'administrative' if (administrative_role && administrative_role == '1')
-
set_roles << 'billing' if (billing_role && billing_role == '1')
-
set_roles << 'technical' if (technical_role && technical_role == '1')
-
set_roles << 'validation' if (validation_role && validation_role == '1')
-
unless set_roles.empty?
-
self.roles = set_roles
-
end
-
if roles.blank? && (type !='Registrant')
-
self.roles = ['administrative']
-
end
-
end
-
-
1
def self.optional_contacts?
-
Settings.dynamic_contact_count == "on"
-
end
-
-
1
def show_domains?
-
epki_agreement? || pending_epki?
-
end
-
end
-
class ContactValidationHistory < ActiveRecord::Base
-
belongs_to :validation_history
-
belongs_to :contact
-
end
-
class Country < ActiveRecord::Base
-
BLACKLIST=%w(AF CU ER GN IR IQ LR KP RW SL SY SD SS ZW)
-
PRIORITY = [["United States", "US"], ["United Kingdom", "GB"], ["Canada", "CA"]]
-
-
scope :approved, ->{where{iso1_code << Country::BLACKLIST}}
-
-
def to_param
-
Rails.cache.fetch("#{cache_key}/to_param") do
-
iso1_code
-
end
-
end
-
-
def self.iso1_codes
-
Rails.cache.fetch("Country/iso1_codes") do
-
select(:iso1_code).map(&:iso1_code)
-
end
-
-
end
-
-
def self.accepted_countries
-
Rails.cache.fetch("Country/accepted_countries") do
-
iso1_codes-BLACKLIST
-
end
-
end
-
-
def self.select_options(values="iso1_code")
-
Rails.cache.fetch("Country/select_options/#{values}") do
-
approved.collect {|c| [ c.name, c.send(values.to_sym) ] }.sort{|x,y|x[0]<=>y[0]}
-
end
-
end
-
end
-
require 'zip/zip'
-
require 'zip/zipfilesystem'
-
require 'openssl-extensions/all'
-
require 'digest'
-
require 'net/https'
-
require 'uri'
-
-
class Csr < ActiveRecord::Base
-
extend Memoist
-
include Encodable
-
-
has_many :whois_lookups, :dependent => :destroy
-
has_many :signed_certificates, -> { where(type: nil) }, :dependent => :destroy
-
has_many :shadow_certificates
-
has_many :ca_certificate_requests, as: :api_requestable, dependent: :destroy
-
has_many :sslcom_ca_requests, as: :api_requestable
-
has_many :ca_api_requests, as: :api_requestable
-
has_many :ca_dcv_requests, as: :api_requestable, dependent: :destroy
-
has_many :ca_dcv_resend_requests, as: :api_requestable, dependent: :destroy
-
has_many :domain_control_validations, :dependent => :destroy do
-
def last_sent
-
where{email_address !~ 'null'}.last
-
end
-
-
def last_emailed
-
where{(email_address !~ 'null') & (dcv_method >> [nil,'email'])}.last
-
end
-
-
def last_method
-
where{dcv_method >> ['http','https','email']}.last
-
end
-
end
-
has_many :csr_unique_values, :dependent => :destroy
-
has_one :csr_override #used for overriding csr fields - does not include a full csr
-
belongs_to :certificate_content, touch: true
-
belongs_to :certificate_lookup
-
belongs_to :ssl_account, touch: true
-
has_one :certificate_order, :through=>:certificate_content
-
has_many :certificate_orders, :through=>:certificate_content # api_requestable.certificate_orders compatibility
-
serialize :subject_alternative_names
-
validates_presence_of :body
-
# validates_presence_of :common_name, :if=> "!body.blank?", :message=> "field blank. Invalid csr."
-
# validates_uniqueness_of :unique_value, scope: :public_key_sha1
-
-
#will_paginate
-
cattr_accessor :per_page
-
@@per_page = 10
-
-
scope :sslcom, ->{joins{certificate_content}.where.not certificate_contents: {ca_id: nil}}
-
-
scope :search, lambda { |term|
-
where("MATCH (common_name, body, decoded) AGAINST ('#{term}')")
-
}
-
-
scope :pending, ->{joins(:certificate_content).
-
where{certificate_contents.workflow_state >> ['pending_validation', 'validated']}.
-
order("certificate_contents.updated_at asc")}
-
-
scope :range, lambda{|start, finish|
-
if start.is_a? String
-
s= start =~ /\// ? "%m/%d/%Y" : "%m-%d-%Y"
-
f= finish =~ /\// ? "%m/%d/%Y" : "%m-%d-%Y"
-
start = Date.strptime start, s
-
finish = Date.strptime finish, f
-
end
-
where{updated_at >> (start..finish)}} do
-
end
-
-
BEGIN_TAG="-----BEGIN CERTIFICATE REQUEST-----"
-
END_TAG="-----END CERTIFICATE REQUEST-----"
-
BEGIN_NEW_TAG="-----BEGIN NEW CERTIFICATE REQUEST-----"
-
END_NEW_TAG="-----END NEW CERTIFICATE REQUEST-----"
-
-
COMMAND=->(key_file){%x"openssl rsa -pubin -in #{key_file} -text -noout"}
-
TIMEOUT_DURATION=10
-
-
before_create do |csr|
-
csr.ref = generate_ref
-
end
-
-
after_create do |c|
-
tmp_file = "#{Rails.root}/tmp/csr_pub-#{DateTime.now.to_i}.key"
-
File.open(tmp_file, 'wb') do |f|
-
f.write c.public_key
-
end
-
modulus = Timeout.timeout(TIMEOUT_DURATION) do
-
COMMAND.call tmp_file
-
end
-
c.update_column(:modulus, modulus)
-
File.delete(tmp_file) if File.exist?(tmp_file)
-
end
-
-
after_save do |c|
-
c.certificate_content.touch unless c.certificate_content.blank?
-
c.certificate_order.touch unless c.certificate_content.blank?
-
-
end
-
-
# def to_param
-
# ref
-
# end
-
-
def unique_value
-
if certificate_content.blank? or certificate_content.ca.blank?
-
csr_unique_value.unique_value
-
else
-
if ca_certificate_requests.first and !ca_certificate_requests.first.unique_value.blank?
-
ca_certificate_requests.first.unique_value # comodo has returned a unique already
-
else
-
if csr_unique_values.empty?
-
if new_record?
-
csr_unique_values.build(unique_value: SecureRandom.hex(5)) # generate our own
-
else
-
csr_unique_values.create(unique_value: SecureRandom.hex(5)) # generate our own
-
end
-
end
-
csr_unique_values.last.unique_value
-
end
-
end
-
end
-
memoize :unique_value
-
-
def csr_unique_value
-
last_unique_value = csr_unique_values.last
-
#if unique_value is expired, then new unique_value should be generated
-
if last_unique_value.nil? or (Date.today-last_unique_value.created_at.to_date).to_i > 30
-
last_unique_value = new_record? ?
-
csr_unique_values.build(unique_value: SecureRandom.hex(5)) :
-
csr_unique_values.create(unique_value: SecureRandom.hex(5))
-
end
-
last_unique_value
-
end
-
memoize :csr_unique_value
-
-
def common_name_to_unicode
-
SimpleIDN.to_unicode(read_attribute(:common_name)).gsub(/\x00/, '') unless read_attribute(:common_name).blank?
-
end
-
-
def body=(csr)
-
csr=Csr.enclose_with_tags(csr.strip)
-
unless Settings.csr_parser=="remote"
-
self[:body] = csr
-
begin
-
parsed = OpenSSL::X509::Request.new csr
-
rescue
-
location = "CertificateContent.id=#{certificate_content.id}=>" if
-
certificate_content
-
location +="Csr.id=#{id}=>" unless id.blank?
-
logger.error "could not parse #{location || 'unknown'} for #{csr}"
-
errors.add :base, 'error: could not parse csr'
-
else
-
self[:common_name] = parsed.subject.common_name
-
self[:organization] = force_string_encoding(parsed.subject.organization)
-
self[:organization_unit] = force_string_encoding(parsed.subject.organizational_unit)
-
self[:state] = force_string_encoding(parsed.subject.region)
-
self[:locality] = force_string_encoding(parsed.subject.locality)
-
self[:country] = force_string_encoding(parsed.subject.country)
-
self[:email] = parsed.subject.email
-
self[:sig_alg] = parsed.signature_algorithm
-
self[:subject_alternative_names] = parsed.subject_alternative_names
-
begin
-
self[:strength] = parsed.strength
-
self[:challenge_password] = parsed.challenge_password?
-
rescue
-
end
-
end
-
else
-
ssl_util = Savon::Client.new Settings.csr_parser_wsdl
-
self[:body] = csr
-
begin
-
response = ssl_util.parse_csr do |soap|
-
soap.body = {:csr => csr}
-
end
-
rescue
-
location = "CertificateContent.id=#{certificate_content.id}=>" if
-
certificate_content
-
location +="Csr.id=#{id}=>" unless id.blank?
-
certificate_content
-
logger.error "could not parse #{location || 'unknown'} for #{csr}"
-
else
-
parsed = response.to_hash[:multi_ref]
-
self[:duration] = parsed[:duration] unless parsed[:duration].is_a? Hash
-
self[:common_name] = parsed[:common_name] unless parsed[:common_name].is_a? Hash
-
self[:organization] = parsed[:organization] unless parsed[:organization].is_a? Hash
-
self[:organization_unit] = parsed[:organization_unit] unless parsed[:organization_unit].is_a? Hash
-
self[:state] = parsed[:state] unless parsed[:state].is_a? Hash
-
self[:locality] = parsed[:locality] unless parsed[:locality].is_a? Hash
-
self[:country] = parsed[:country] unless parsed[:country].is_a? Hash
-
self[:email] = parsed[:email] unless parsed[:email].is_a? Hash
-
self[:sig_alg] = parsed[:sig_alg] unless parsed[:sig_alg].is_a? Hash
-
end
-
end
-
end
-
-
def self.remove_begin_end_tags(csr)
-
csr.gsub!(/-+BEGIN.+?REQUEST-+/,"") if csr =~ /-+BEGIN.+?REQUEST-+/
-
csr.gsub!(/-+END.+?REQUEST-+/,"") if csr =~ /-+END.+?REQUEST-+/
-
csr
-
end
-
-
def sslcom_approval_ids
-
sslcom_ca_requests.unexpired.pluck(:approval_id)
-
end
-
-
def sslcom_usernames
-
sslcom_ca_requests.unexpired.pluck(:username)
-
end
-
-
def sslcom_outstanding_approvals
-
status=SslcomCaApi.get_status(csr: self, mapping: certificate_content.ca)[1].body
-
if status=="[]" or status.blank?
-
0
-
else
-
JSON.parse(status)
-
end
-
end
-
-
def self.enclose_with_tags(csr)
-
csr=remove_begin_end_tags(csr)
-
unless (csr =~ Regexp.new(BEGIN_TAG))
-
csr.gsub!(/-+BEGIN (NEW )?CERTIFICATE REQUEST-+/,"")
-
csr = BEGIN_TAG + "\n" + csr.strip
-
end
-
unless (csr =~ Regexp.new(END_TAG))
-
csr.gsub!(/-+END (NEW )?CERTIFICATE REQUEST-+/,"")
-
csr = csr + "\n" unless csr=~/\n\Z\z/
-
csr = csr + END_TAG + "\n"
-
end
-
csr
-
end
-
-
def to_api
-
CGI::escape(body)
-
end
-
-
def is_ip_address?
-
CertificateContent.is_ip_address?(common_name)
-
end
-
-
def is_server_name?
-
CertificateContent.is_server_name?(common_name)
-
end
-
-
def is_fqdn?
-
CertificateContent(common_name)
-
end
-
-
def is_intranet?
-
CertificateContent.is_intranet?(common_name)
-
end
-
-
def is_tld?
-
CertificateContent.is_tld?(common_name)
-
end
-
-
def top_level_domain
-
CertificateContent.top_level_domain(common_name)
-
end
-
-
def last_dcv
-
(domain_control_validations.last.try(:dcv_method)=~/https?/) ?
-
domain_control_validations.last : domain_control_validations.last_sent
-
end
-
-
def non_wildcard_name
-
CertificateContent.non_wildcard_name(common_name)
-
end
-
-
# secure is for https, domain is to override the csr subject
-
def dcv_url(secure=false, domain=nil)
-
"http#{'s' if secure}://#{domain || non_wildcard_name}/.well-known/pki-validation/#{md5_hash}.txt"
-
end
-
-
def cname_destination
-
"#{dns_sha2_hash}.#{ca_tag}"
-
end
-
-
def ca_tag
-
if certificate_content.blank? # for prevalidating domain with csr
-
"ssl.com"
-
else
-
caa_issuers = certificate_content.ca.try(:caa_issuers)
-
(caa_issuers[0] unless caa_issuers.blank?) || 'comodoca.com'
-
end
-
end
-
-
def dcv_contents
-
"#{sha2_hash}\n#{ca_tag}#{"\n#{self.unique_value}" unless self.unique_value.blank?}"
-
end
-
-
def all_names(options={})
-
(subject_alternative_names and options[:san]) ? (subject_alternative_names.split(",") + [common_name]).flatten.uniq :
-
[common_name]
-
end
-
-
def whois_lookup
-
if whois_lookups.empty?
-
whois_lookups.create
-
else
-
whois_lookups.last
-
end
-
end
-
-
def update_whois_lookup
-
whois_lookups.create
-
end
-
-
def signed_certificate_by_text=(text)
-
return if text.blank?
-
sc = SignedCertificate.create(body: text, csr_id: self.id)
-
unless sc.errors.empty?
-
logger.error "error #{self.model_and_id} signed_certificate_by_text="
-
logger.error sc.errors.to_a.join(": ").to_s
-
logger.error text
-
end
-
sc
-
end
-
-
def openssl_request
-
begin
-
OpenSSL::X509::Request.new(body)
-
rescue Exception=>e
-
logger.error e.backtrace.inspect
-
nil
-
end
-
end
-
-
def public_key
-
openssl_request.public_key if openssl_request
-
end
-
-
def verify_signature
-
openssl_request.verify public_key if openssl_request
-
end
-
-
def public_key_sha1
-
if new_record?
-
public_key_hash(false)
-
else
-
Rails.cache.fetch("#{cache_key}/public_key_sha1") do
-
public_key_hash(true)
-
end
-
end
-
end
-
memoize :public_key_sha1
-
-
def decode
-
begin
-
openssl_request.to_text if body and openssl_request
-
rescue Exception
-
end
-
end
-
-
def self.decode_all
-
self.find_each {|s|
-
begin
-
s.update_column(:decoded, s.decode.scrub) if s.decode
-
rescue Exception
-
end
-
}
-
end
-
-
def signed_certificate_by_text
-
signed_certificate.try(:body)
-
end
-
-
def signed_certificate=(signed_certificate)
-
signed_certificates << signed_certificate
-
end
-
-
def signed_certificate
-
signed_certificates.order(:created_at).last
-
end
-
memoize :signed_certificate
-
-
def replace_csr(csr)
-
update_attribute :body, csr
-
certificate_content.update_attribute(:workflow_state, "contacts_provided") if
-
certificate_content.pending_validation?
-
end
-
-
def sig_alg_parameter
-
SslcomCaApi.sig_alg_parameter(self)
-
end
-
-
def options_for_ca_dcv
-
{}.tap do |options|
-
options.merge!(
-
'domainName' => common_name)
-
end
-
end
-
-
def country
-
case read_attribute(:country)
-
when /united states.+/i, /usa/i
-
"US"
-
when /UK/i, /great britain.+/i, /england/i, /united kingdom.+/i
-
"GB"
-
else
-
read_attribute(:country).blank? ? "" : read_attribute(:country).upcase
-
end
-
end
-
-
def sent_success(with_order_num=false)
-
ca_certificate_requests.all.find{|cr|cr.success? && (with_order_num ? cr.order_number : true)}
-
end
-
-
#TODO need to convert to dem - see http://support.citrix.com/article/CTX106631
-
def md5_hash
-
Digest::MD5.hexdigest(to_der).upcase unless body.blank?
-
end
-
-
def sha1_hash
-
Digest::SHA1.hexdigest(to_der).upcase unless body.blank?
-
end
-
-
def sha2_hash
-
Digest::SHA2.hexdigest(to_der).upcase unless body.blank?
-
end
-
-
def dns_md5_hash
-
"_#{md5_hash}"
-
end
-
-
def dns_sha2_hash
-
"#{sha2_hash[0..31]}.#{sha2_hash[32..63]}#{".#{self.unique_value}" unless self.unique_value.blank?}"
-
end
-
memoize :dns_sha2_hash
-
-
def to_der
-
to_openssl.to_der
-
rescue
-
""
-
end
-
-
def to_openssl
-
OpenSSL::X509::Request.new body
-
rescue
-
""
-
end
-
-
def days_left
-
SiteCheck.days_left(self.non_wildcard_name, true)
-
end
-
-
def generate_ref
-
'csr-'+SecureRandom.hex(1)+Time.now.to_i.to_s(32)
-
end
-
-
def ref
-
if read_attribute(:ref).blank?
-
write_attribute(:ref, generate_ref)
-
save unless new_record?
-
end
-
read_attribute(:ref)
-
end
-
-
def run_last_ca_request
-
scr=sslcom_ca_requests.first
-
req,res=scr.call_again
-
api_log_entry=SslcomCaRequest.create(request_url: scr.request_url, parameters: req.body,
-
method: 'post', response: res.try(:body), ca: scr.ca)
-
branded_sub_ca=nil
-
Ca::SSL_ACCOUNT_MAPPING.each{|k,v|v.map{|k,v|branded_sub_ca=k; break if v==scr.ca}}
-
ca = Ca.find_by_ca_name(branded_sub_ca || scr.ca)
-
attrs = {body: api_log_entry.end_entity_certificate.to_s, ca_id: ca.id}
-
sc=signed_certificates.create(attrs)
-
sc.sslcom_ca_requests << api_log_entry
-
end
-
-
def get_ejbca_certificate(user_name)
-
url=SslcomCaApi.ca_host + "/v1/certificate_chain"
-
req,res=SslcomCaApi.call_ca(url,{},
-
SslcomCaApi.retrieve_cert_json(user_name: user_name))
-
api_log_entry=SslcomCaRequest.create(request_url: url, parameters: req.body,
-
method: 'post', response: res.try(:body))
-
if res.message=="OK"
-
attrs = {body: api_log_entry.end_entity_certificate.to_s, ejbca_username: user_name}
-
sc=signed_certificates.create(attrs)
-
sc.sslcom_ca_requests << api_log_entry
-
sc
-
end
-
end
-
-
private
-
-
def public_key_hash(save_to_db=false)
-
begin
-
if read_attribute(:public_key_sha1).blank?
-
write_attribute(:public_key_sha1, OpenSSL::Digest::SHA1.new(public_key.to_der).to_s)
-
save if save_to_db
-
end
-
read_attribute(:public_key_sha1)
-
rescue Exception => e
-
logger.error e.backtrace.inspect
-
nil
-
end
-
end
-
end
-
class CsrOverride < ActiveRecord::Base
-
belongs_to :csr
-
end
-
-
class CsrUniqueValue < ActiveRecord::Base
-
belongs_to :csr
-
has_many :domain_control_validations
-
-
validates_presence_of :csr
-
validates_each :unique_value do |record, attr, value|
-
record.errors.add(attr, "is not unique to public key SHA1 #{record.csr.public_key_sha1}") if
-
Csr.joins(:csr_unique_values).where{(csr_unique_values.unique_value==value) &
-
(public_key_sha1==record.csr.public_key_sha1)}.count>1
-
end
-
end
-
class DailyInvoice < Invoice
-
-
START_DATE = DateTime.now.beginning_of_day
-
END_DATE = DateTime.now.end_of_day
-
-
def self.invoice_exists?(ssl_account_id)
-
ssl = SslAccount.find ssl_account_id
-
ssl && ssl.daily_invoices
-
.where(start_date: START_DATE, status: 'pending').any?
-
end
-
-
def self.get_current_invoice(ssl_account_id)
-
ssl = SslAccount.find ssl_account_id
-
if ssl
-
ssl.daily_invoices.order(created_at: :desc)
-
.where(start_date: START_DATE, status: 'pending').first
-
else
-
nil
-
end
-
end
-
-
def self.last_invoice_for_day(ssl_account_id, exclude=nil)
-
ssl = SslAccount.find ssl_account_id
-
ssl.daily_invoices.order(id: :desc)
-
.where(start_date: START_DATE).where.not(id: exclude).first
-
end
-
end
-
class Db < ActiveRecord::Base
-
-
# create initial local and global sandboxes
-
# be sure db sandbox_ssl_com exists and is accessible
-
def self.init_sandboxes
-
Db.delete_all
-
Sandbox.delete_all
-
sandbox_db=Db.create name: "sandbox_ssl_com"
-
%w(com local).each do |extension|
-
Sandbox.create host: "sandbox.ssl.#{extension}", api_host: "sws-test.sslpki.#{extension}",
-
name: "Production Sandbox Site", db_id: sandbox_db.id # production sandbox
-
Sandbox.create host: "sandbox2.ssl.#{extension}", api_host: "sws-test2.sslpki.#{extension}", name: "Development Sandbox Site",
-
db_id: sandbox_db.id #dev sandbox
-
#to prevent recursive look ups, create the Websites and Db in the sandbox db
-
end
-
Sandbox.find_by_host("sandbox2.ssl.local").use_database #switch to the sandbox db
-
Db.delete_all
-
Sandbox.delete_all
-
sandbox_db=Db.create name: "sandbox_ssl_com"
-
%w(com local).each do |extension|
-
Sandbox.create host: "sandbox.ssl.#{extension}", api_host: "sws-test.sslpki.#{extension}",
-
name: "Production Sandbox Site", db_id: sandbox_db.id
-
Sandbox.create host: "sandbox2.ssl.#{extension}", api_host: "sws-test2.sslpki.#{extension}",
-
name: "Development Sandbox Site", db_id: sandbox_db.id
-
Website.revert_database #switch back
-
end
-
end
-
end
-
class Deposit < ActiveRecord::Base
-
acts_as_sellable :cents => :amount, :currency => false
-
has_many :orders, ->{includes(:stored_preferences)}, :through => :line_items
-
-
-
def price=(amount)
-
self.amount = amount.gsub(/\./,"").to_i
-
end
-
-
def order
-
orders.last
-
end
-
-
protected
-
-
def validate
-
errors.add(:price, "must be greater than 0") if price.nil? or price.cents <= 0
-
end
-
end
-
# https://anotherengineeringblog.com/extract-parse-digital-certificates-with-ruby
-
-
require 'delegate'
-
require 'date'
-
-
class DigitalCertificate < SimpleDelegator
-
def subject
-
__getobj__.subject.to_s
-
end
-
-
def issuer
-
__getobj__.issuer.to_s
-
end
-
-
def serial
-
__getobj__.serial.to_s(16).scan(/.{1,2}/).join(' ')
-
end
-
-
def extensions
-
__getobj__.extensions.map(&:value)
-
end
-
-
def valid_from
-
__getobj__.not_before.to_s
-
end
-
-
def valid_to
-
__getobj__.not_after.to_s
-
end
-
-
def thumbprint
-
OpenSSL::Digest::SHA1.new(__getobj__.to_der).to_s.upcase
-
end
-
-
def root_certificate?(subjects)
-
!subjects.include?(issuer) && !time_stamping_certificate?
-
end
-
-
def time_stamping_certificate?
-
extension_match = extensions.any? { |ext| ext =~ /time\s*stamp/i }
-
extension_match || subject =~ /time\s*stamp/i
-
end
-
-
def to_db
-
{ issuer: issuer, subject: subject, serial_no: serial,
-
thumbprint: thumbprint, algorithm: signature_algorithm,
-
valid_from: DateTime.parse(valid_from),
-
valid_to: DateTime.parse(valid_to)
-
}
-
end
-
end
-
# https://anotherengineeringblog.com/extract-parse-digital-certificates-with-ruby
-
-
class DigitalCertificateParser
-
attr_reader :all_certificates
-
-
def initialize(digital_signature)
-
if !digital_signature.instance_of?(OpenSSL::PKCS7)
-
raise InvalidSignatureError, 'Signature is not a PKCS7'
-
end
-
@all_certificates = digital_signature.certificates.map do |cert|
-
DigitalCertificate.new(cert)
-
end
-
end
-
-
def chains
-
@chains ||= build_chains
-
end
-
-
def end_user_certificate
-
first_chain = chains[0]
-
first_chain.last if first_chain
-
end
-
-
def root_certificate
-
first_chain = chains[0]
-
first_chain.first if first_chain
-
end
-
-
private
-
-
def build_chains
-
chains = []
-
root_certs = find_root_certs
-
root_certs.each_with_index do |cert, index|
-
chains[index] = [cert]
-
while (next_certificate = find_next_in_chain(chains[index].last))
-
chains[index] << next_certificate
-
end
-
end
-
chains
-
end
-
-
def find_next_in_chain(parent_cert)
-
all_certificates.find do |cert|
-
cert.issuer == parent_cert.subject && !cert.time_stamping_certificate?
-
end
-
end
-
-
def find_root_certs
-
subjects = all_certificates.map(&:subject)
-
all_certificates.select do |certificate|
-
certificate.root_certificate?(subjects.delete(certificate.subject))
-
end
-
end
-
end
-
-
class Discount < ActiveRecord::Base
-
has_and_belongs_to_many :certificates
-
has_and_belongs_to_many :orders
-
belongs_to :benefactor, polymorphic: true
-
-
APPLY_AS = [:percentage, :absolute]
-
-
#this used to be the default scopr but upgrading to Rails 4.2 'broke' it
-
scope :viable, ->{where{(status >> [nil, 'active']) & ((remaining > 0) | (remaining >> [nil])) &
-
((expires_at >> [nil]) | (expires_at >= Date.today))}}
-
-
scope :general, ->{where{((benefactor_id==nil) & (benefactor_type==nil))}}
-
-
scope :include_all, lambda {Discount.unscoped}
-
end
-
class Domain < CertificateName
-
belongs_to :ssl_account, touch: true
-
has_many :certificate_order_domains, dependent: :destroy
-
-
#will_paginate
-
cattr_accessor :per_page
-
@@per_page = 10
-
-
cattr_accessor :csr_per_page
-
@@csr_per_page = 10
-
-
scope :expired_validation, -> {
-
joins(:domain_control_validations)
-
.where('domain_control_validations.id = (SELECT MAX(domain_control_validations.id) FROM domain_control_validations WHERE domain_control_validations.certificate_name_id = certificate_names.id)')
-
.where{(domain_control_validations.responded_at < DomainControlValidation::MAX_DURATION_DAYS[:email].days.ago.to_date)}
-
}
-
-
scope :search_domains, lambda {|term|
-
term ||= ""
-
term = term.strip.split(/\s(?=(?:[^']|'[^']*')*$)/)
-
filters = { email: nil, name: nil, expired_validation: nil }
-
-
filters.each {|fn, fv|
-
term.delete_if {|str| str =~ Regexp.new(fn.to_s + "\\:\\'?([^']*)\\'?"); filters[fn] ||= $1; $1}
-
}
-
-
term = term.empty? ? nil : term.join(" ")
-
-
return nil if [term, *(filters.values)].compact.empty?
-
-
result = self.all
-
unless term.blank?
-
result = result.where{
-
(email =~ "%#{term}%") |
-
(name =~ "%#{term}%")
-
}
-
end
-
-
%w(expired_validation).each do |field|
-
query = filters[field.to_sym]
-
result = result.expired_validation if query
-
end
-
-
result.uniq.order(created_at: :desc)
-
}
-
end
-
require 'public_suffix'
-
-
class DomainControlValidation < ActiveRecord::Base
-
has_many :ca_dcv_requests, as: :api_requestable, dependent: :destroy
-
belongs_to :csr, touch: true # only for single domain certs
-
belongs_to :csr_unique_value
-
belongs_to :certificate_name, touch: true # only for UCC or multi domain certs
-
delegate :certificate_content, to: :csr
-
# belongs_to :domain, class_name: "CertificateName"
-
# delegate :ssl_account, to: :domain
-
serialize :candidate_addresses
-
belongs_to :validation_compliance
-
-
# validate :email_address_check, unless: lambda{|r| r.email_address.blank?}
-
-
IS_INVALID = "is an invalid email address choice"
-
FAILURE_ACTION = %w(ignore reject)
-
AUTHORITY_EMAIL_ADDRESSES = %w(admin@ administrator@ webmaster@ hostmaster@ postmaster@)
-
MAX_DURATION_DAYS={email: 820}
-
-
EMAIL_CHOICE_CACHE_EXPIRES_DAYS=1
-
-
default_scope{ order("domain_control_validations.created_at asc")}
-
scope :global, -> {where{(certificate_name_id==nil) & (csr_id==nil)}}
-
scope :whois_threshold, -> {where(updated_at: 1.hour.ago..DateTime.now)}
-
scope :satisfied, -> {where(workflow_state: "satisfied")}
-
-
include Workflow
-
workflow do
-
state :new do
-
event :send_dcv, :transitions_to => :sent_dcv
-
event :hashing, :transitions_to => :hashed
-
event :satisfy, :transitions_to => :satisfied
-
end
-
-
state :hashed do
-
event :satisfy, :transitions_to => :satisfied
-
end
-
-
state :sent_dcv do
-
event :satisfy, :transitions_to => :satisfied
-
-
on_entry do
-
self.update_attribute :sent_at, DateTime.now
-
end
-
end
-
-
state :satisfied do
-
on_entry do
-
hash_satisfied unless dcv_method=~/email/
-
self.validation_compliance_id=
-
case dcv_method
-
when /email/
-
2
-
when /http/
-
6
-
when /cname/
-
7
-
end
-
self.identifier_found=true
-
self.responded_at=DateTime.now
-
self.save
-
end
-
end
-
end
-
-
def email_address_check
-
errors.add(:email_address, "'#{email_address}' "+IS_INVALID) unless
-
DomainControlValidation.approved_email_address? candidate_addresses, email_address
-
end
-
-
def send_to(address)
-
update_attributes email_address: address, sent_at: DateTime.now, dcv_method: "email"
-
if csr.sent_success
-
ComodoApi.auto_update_dcv(dcv: self)
-
co=csr.certificate_content.certificate_order
-
co.valid_recipients_list.each do |c|
-
OrderNotifier.dcv_sent(c, co, self).deliver!
-
end
-
end
-
end
-
-
# assume this belongs to a certificate_name which belongs to an ssl_account
-
def hash_satisfied
-
prepend=""
-
self.identifier,self.address_to_find_identifier= certificate_name.blank? ? [false,false] :
-
case dcv_method
-
when /https/
-
["#{certificate_name.csr.sha2_hash}\n#{certificate_name.ca_tag}#{"\n#{certificate_name.csr.unique_value}" unless
-
certificate_name.csr.unique_value.blank?}",
-
certificate_name.dcv_url(true,prepend, true)]
-
when /http/
-
["#{certificate_name.csr.sha2_hash}\n#{certificate_name.ca_tag}#{"\n#{certificate_name.csr.unique_value}" unless certificate_name.csr.unique_value.blank?}",
-
certificate_name.dcv_url(false,prepend, true)]
-
when /cname/
-
[certificate_name.cname_destination,
-
certificate_name.cname_origin(true)]
-
end
-
end
-
-
# the 24 hour limit no longer applies, but will keep this in case we need it again
-
#def is_eligible_to_send?
-
# !email_address.blank? && updated_at > 24.hours.ago && !satisfied?
-
#end
-
-
def is_eligible_to_resend?
-
!email_address.blank? && !satisfied?
-
end
-
alias :is_eligible_to_send? :is_eligible_to_resend?
-
-
def method_for_api(options={http_csr_hash: "http_csr_hash", https_csr_hash: "https_csr_hash",
-
cname_csr_hash: "cname_csr_hash", email: self.email_address})
-
case dcv_method
-
when "http", "http_csr_hash"
-
options[:http_csr_hash]
-
when "https", "https_csr_hash"
-
options[:https_csr_hash]
-
when "cname", "cname_csr_hash"
-
options[:cname_csr_hash]
-
when "email"
-
options[:email]
-
end
-
end
-
-
def self.ssl_account(domain)
-
SslAccount.unscoped.joins{certificate_names.domain_control_validations}.joins{certificate_contents.certificate_names.domain_control_validations}.where{(certificate_names.domain_control_validations.subject=~domain) or
-
(certificate_contents.certificate_names.domain_control_validations.subject=~domain)}
-
end
-
-
def ssl_account
-
SslAccount.unscoped.joins{domains.domain_control_validations.outer}.where(domain_control_validations: {id: self.id})
-
end
-
-
# this will find multi-level subdomains from a more root level domain
-
def self.satisfied_validation(ssl_account,domain,public_key_sha1=nil)
-
name=domain.downcase
-
name=('%'+name[1..-1]) if name[0]=="*" # wildcard
-
DomainControlValidation.joins(:certificate_name).where{(identifier_found==1) &
-
(certificate_name.name=~"#{name}") &
-
(certificate_name_id >> [ssl_account.all_certificate_names(name,"validated").pluck(:id)])}.each do |dcv|
-
return dcv if dcv.validated?(name,public_key_sha1)
-
end
-
end
-
-
def self.validated?(ssl_account,domain,public_key_sha1=nil)
-
satisfied_validation(ssl_account,domain,public_key_sha1).blank? ? false : true
-
end
-
-
def cached_csr_public_key_sha1
-
Rails.cache.fetch("#{cache_key}/cached_csr_public_key_sha1") do
-
csr.public_key_sha1
-
end
-
end
-
-
def cached_csr_public_key_md5
-
Rails.cache.fetch("#{cache_key}/cached_csr_public_key_md5") do
-
csr.public_key_md5
-
end
-
end
-
-
# is this dcv validated?
-
# domain - against a domain that may or many not be satisfied by this validation
-
# public_key_sha1 - against a csr
-
def validated?(domain=nil,public_key_sha1=nil)
-
satisfied = ->(public_key_sha1){
-
cert_req=(csr || certificate_name.csr).try(:public_key_sha1) if public_key_sha1
-
identifier_found && !responded_at.blank? &&
-
responded_at > DomainControlValidation::MAX_DURATION_DAYS[:email].days.ago &&
-
(!email_address.blank? or (public_key_sha1 ?
-
cert_req.try(:downcase)==public_key_sha1.downcase : true))
-
}
-
(domain ? DomainControlValidation.domain_in_subdomains?(domain,certificate_name.name) : true) and
-
satisfied.call(public_key_sha1)
-
end
-
-
# this determines if a domain validation will satisfy another domain validation based on 2nd level subdomains and wildcards
-
# BE VERY CAREFUL as this drives validation for the entire platform including Web and API
-
def self.domain_in_subdomains?(subject,compare_with)
-
subject=subject[2..-1] if subject=~/\A\*\./
-
compare_with=compare_with[2..-1] if compare_with=~/\A\*\./
-
if ::PublicSuffix.valid?(subject, default_rule: nil) and ::PublicSuffix.valid?(compare_with, default_rule: nil)
-
d=::PublicSuffix.parse(compare_with)
-
compare_with_subdomains = d.trd ? d.trd.split(".").reverse : []
-
0.upto(compare_with_subdomains.count) do |i|
-
return true if ((compare_with_subdomains.slice(0,i).reverse<<d.domain).join("."))==subject
-
end
-
end
-
false
-
end
-
-
def verify_http_csr_hash
-
certificate_name.dcv_verify(dcv_method)
-
end
-
-
def email_address_choices
-
name = (csr.blank? ? certificate_name_id.nil? ? subject : certificate_name.name : csr.common_name)
-
DomainControlValidation.email_address_choices(name)
-
end
-
-
def self.email_address_choices(name)
-
name=CertificateContent.non_wildcard_name(name)
-
Rails.cache.fetch("email_address_choices/#{name}", expires_in: EMAIL_CHOICE_CACHE_EXPIRES_DAYS.days) do
-
return [] unless DomainNameValidator.valid?(name,false)
-
d=::PublicSuffix.parse(name.downcase)
-
subdomains = d.trd ? d.trd.split(".") : []
-
subdomains.shift if subdomains[0]=="*" #remove wildcard
-
[].tap {|s|
-
0.upto(subdomains.count) do |i|
-
if i==0
-
s << d.domain
-
else
-
s << (subdomains.slice(-i,subdomains.count)<<d.domain).join(".")
-
end
-
end
-
}.map do |e|
-
AUTHORITY_EMAIL_ADDRESSES.map do |ae|
-
ae+e
-
end
-
end.flatten
-
end
-
end
-
-
def self.approved_email_address?(choices, selection)
-
choices.include? selection
-
end
-
-
def comodo_email_address_choices
-
write_attribute(:candidate_addresses, ComodoApi.domain_control_email_choices(certificate_name.name).email_address_choices)
-
save(validate: false)
-
end
-
-
def candidate_addresses
-
if read_attribute(:candidate_addresses).blank?
-
# delay.comodo_email_address_choices
-
email_address_choices
-
else
-
read_attribute(:candidate_addresses)
-
end
-
end
-
-
def friendly_action
-
-
end
-
-
def action_performed
-
"#{method_for_api({http_csr_hash: "scanning for #{certificate_name.dcv_url}",
-
https_csr_hash: "scanning for #{certificate_name.dcv_url}",
-
cname_csr_hash: "scanning for CNAME: #{certificate_name.cname_origin} -> #{certificate_name.cname_destination}",
-
email: "sent validation to #{self.email_address}"})}"
-
end
-
-
end
-
class DomainNameValidator < ActiveModel::EachValidator
-
-
def validate_each(record, attribute, value)
-
if value.is_a? Array
-
value.each do |val|
-
record.errors[attribute] << (options[:message] || "#{val} is not a valid domain name") unless
-
DomainNameValidator.valid?(val)
-
end
-
else
-
record.errors[attribute] << (options[:message] || "#{value} is not a valid domain name") unless
-
DomainNameValidator.valid?(value)
-
end
-
end
-
-
def self.valid?(domain,wildcard=true)
-
regex = wildcard ? /[^a-zA-Z0-9\.\*-]+/ : /[^a-zA-Z0-9\.-]+/
-
(CertificateContent.is_ip_address?(domain) ||
-
PublicSuffix.valid?(domain)) and !(domain =~ regex)
-
end
-
end
-
class DomainValidation < Validation
-
has_many :certificate_contents
-
end
-
class DuoAccount < ActiveRecord::Base
-
belongs_to :ssl_account
-
-
validates :duo_akey, length: { minimum: 40 }
-
attr_encrypted :duo_ikey, :duo_skey, :duo_akey, :duo_hostname, :key => Rails.application.secrets.secret_key_base,algorithm: 'aes-256-cbc', :mode => :per_attribute_iv_and_salt, insecure_mode: true
-
-
after_initialize do
-
if new_record?
-
self.duo_akey ||= SecureRandom.base64(40)
-
end
-
end
-
-
def reset_secret_key
-
update_attribute :duo_akey, SecureRandom.base64(40)
-
end
-
end
-
class DuplicateV2User < ActiveRecord::Base
-
belongs_to :user
-
has_many :legacy_v2_user_mappings, :as=>:user_mappable
-
-
IGNORE = %w(leo@ssl.com rabbit sy_adm1n buttysquirrel)
-
-
def source_obj
-
m = V2MigrationProgress.find_by_migratable(self)
-
m.last.source_obj unless m.blank?
-
end
-
-
def v2_migration_progress
-
m = V2MigrationProgress.find_by_migratable(self, :all)
-
end
-
-
def self.find_and_notify(params)
-
if dup = find_by_login(params[:login]) || find_by_email(params[:email])
-
DuplicateV2UserMailer.duplicate_found(dup).deliver!
-
else
-
false
-
end
-
end
-
-
def self.find_mismatch
-
[].tap do |mm|
-
all.select do |d|
-
so = d.source_obj
-
unless so.blank?
-
mm << so if (so.login!=d.login || so.email!=d.email)
-
end
-
end
-
end
-
end
-
-
def self.mismatched_attributes
-
[].tap do |mm|
-
all.each do |d|
-
so = d.source_obj
-
unless so.blank?
-
mm << [[d.login, d.email],[so.login, so.email]] if (so.login!=d.login || so.email!=d.email)
-
end
-
end
-
end
-
end
-
-
def self.sync_mismatched_attributes
-
[].tap do |mm|
-
all.each do |d|
-
so = d.source_obj
-
unless so.blank?
-
d.update_attributes(login: so.login, email: so.email) if (so.login!=d.login || so.email!=d.email)
-
end
-
end
-
end
-
end
-
-
-
# this function will make accounts with duplicates to use the latest
-
# login with the most "updated_at" changed field the primary login
-
def self.make_latest_login_primary
-
#add each user to a hash
-
users = DuplicateV2User.all.map(&:user).uniq
-
swap=[]
-
users.each do |user|
-
next if IGNORE.include? user.login
-
recent_dup=user.duplicate_v2_users.sort{|a,b|a.updated_at<=>b.updated_at}.last
-
if recent_dup.updated_at.to_date > user.updated_at.to_date
-
swap << user
-
p "#{user.model_and_id} (#{user.login}) being swapped with #{recent_dup.login}"
-
recent_dup.swap_with(user)
-
end
-
end
-
swap
-
end
-
-
#swap attributes and v2_migration_progress
-
def swap_with(user)
-
if (V2MigrationProgress.find_non_mapped(DuplicateV2User)+
-
V2MigrationProgress.find_multiple_mapped(DuplicateV2User)).include? self
-
p "DuplicateV2User #{model_and_id} (#{login}) has no or multiple v2_migration_progresses"
-
elsif (V2MigrationProgress.find_non_mapped(User)+
-
V2MigrationProgress.find_multiple_mapped(User)).include? user
-
p "User #{user.model_and_id} (#{user.login}) has no or multiple v2_migration_progresses"
-
else
-
#swap user<->dup attrs
-
l,p,c,u=user.login, user.crypted_password, user.created_at, user.updated_at
-
so=self.source_obj
-
user.update_attributes(login: self.login,
-
crypted_password: self.password,
-
first_name: so.FirstName,
-
last_name: so.LastName,
-
created_at: self.created_at,
-
updated_at: self.updated_at)
-
self.update_attributes(login: l,
-
password: p,
-
created_at: c,
-
updated_at: u)
-
#swap v2_migration_progress
-
dup=user.v2_migration_progresses.last
-
p "swapping v2_migration_progresses for #{user.model_and_id} and #{dup.model_and_id}"
-
ump=dup
-
vmp=v2_migration_progress.last
-
mtype, mid, mstable, msid=ump.migratable_type, ump.migratable_id, ump.source_table_name, ump.source_id
-
ump.update_attributes migratable_type: vmp.migratable_type,
-
migratable_id: vmp.migratable_id,
-
source_table_name: vmp.source_table_name,
-
source_id: vmp.source_id
-
vmp.update_attributes migratable_type: mtype,
-
migratable_id: mid,
-
source_table_name: mstable,
-
source_id: msid
-
#swap legacy_v2_user_mappings
-
if(!user.legacy_v2_user_mappings.empty? && !legacy_v2_user_mappings.empty?)
-
p "swapping legacy_v2_users for #{user.model_and_id} and #{dup.model_and_id}"
-
ulms=user.legacy_v2_user_mappings
-
dlms=legacy_v2_user_mappings
-
ulms.each do |ulm|
-
p "assigning #{ulm.model_and_id} to #{dup.model_and_id}"
-
ulm.user_mappable=dup
-
ulm.save
-
end
-
dlms.each do |dlm|
-
p "assigning #{dlm.model_and_id} to #{user.model_and_id}"
-
dlm.user_mappable=user
-
dlm.save
-
end
-
end
-
end
-
end
-
-
#temporary function to assist in migration
-
if MIGRATING_FROM_LEGACY
-
def update_record_without_timestamping
-
class << self
-
def record_timestamps; false; end
-
end
-
-
save(false)
-
-
class << self
-
def record_timestamps; super ; end
-
end
-
end
-
end
-
end
-
require 'savon'
-
-
class EjbcaApi
-
def self.connect_ejbca_api
-
client = Savon::Client.new(log_level: :debug,
-
log: true,
-
ssl_cert_file: '/vagrant/config/ssl/leoca.crt',
-
ssl_ca_cert_file: '/vagrant/config/ssl/leocacert.crt',
-
ssl_cert_key_file: '/vagrant/config/ssl/leoca.key',
-
ssl_cert_key_password: '1234',
-
wsdl: "https://192.168.5.17:8443/ejbca/ejbcaws/ejbcaws?wsdl",
-
endpoint: "https://192.168.5.17:8443/ejbca/ejbcaws/ejbcaws")
-
end
-
end
-
-
-
1
class EmailValidator < ActiveModel::EachValidator
-
-
1
EMAIL_FORMAT = Regexp.new('\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b', Regexp::IGNORECASE)
-
-
1
def validate_each(record, attribute, value)
-
4
record.errors[attribute] << (options[:message] || "is not an email address") unless
-
108
value =~ EMAIL_FORMAT
-
end
-
end
-
module Encryption
-
mattr_accessor :algorithm
-
self.algorithm = 'aes-256-cbc'
-
-
def encrypt(data, password, salt)
-
cipher = OpenSSL::Cipher::Cipher.new(algorithm)
-
cipher.encrypt
-
cipher.pkcs5_keyivgen(password, salt)
-
encrypted_data = cipher.update(data)
-
encrypted_data << cipher.final
-
end
-
-
def decrypt(encrypted_data, password, salt)
-
cipher = OpenSSL::Cipher::Cipher.new(algorithm)
-
cipher.decrypt
-
cipher.pkcs5_keyivgen(password, salt)
-
data = cipher.update(encrypted_data)
-
data << cipher.final
-
end
-
-
end
-
class EndEntityProfile < Ca
-
-
end
-
class EnrollmentOrder < Order
-
-
end
-
class EpkiRegistrant < Registrant
-
alias_attribute :constraints, :domains
-
-
end
-
1
class Folder < ActiveRecord::Base
-
1
extend Memoist
-
-
1
belongs_to :ssl_account
-
1
belongs_to :parent, foreign_key: "parent_id", class_name: "Folder"
-
1
has_many :certificate_orders
-
-
1
acts_as_tree dependent: :destroy, order: :name
-
-
1
validates :name,
-
presence: {allow_blank: false},
-
uniqueness: {scope: [:ssl_account_id, :parent_id], case_sensitive: false},
-
format: { with: /\A[\w ]+\z/,
-
message: 'Letters, Numbers, Spaces and Underscores Only'
-
}
-
-
1
after_save :there_can_only_be_one_default_folder
-
1
before_destroy :can_destroy?
-
1
after_destroy :there_can_only_be_one_default_folder
-
1
after_destroy :release_certificate_orders
-
-
1
attr_reader :total_certificate_orders
-
-
1
def cached_certificate_orders
-
CertificateOrder.where(id: (Rails.cache.fetch("#{cache_key}/cached_certificate_orders") do
-
certificate_orders.pluck(:id)
-
end)).includes({certificate_contents: [:signed_certificates, :registrant]}).order(created_at: :desc)
-
end
-
1
memoize :cached_certificate_orders
-
-
1
def get_folder_path
-
if ancestors.any?
-
ancestors.last.self_and_descendants.map(&:name).join('/')
-
else
-
name
-
end
-
end
-
-
1
def self.show_folders?(user=nil)
-
user.is_system_admins? ? false : Settings.folders == "show"
-
end
-
-
1
def folder_contents
-
contents = []
-
@total_certificate_orders = 0
-
if self.descendants.count > 0
-
self.self_and_descendants.includes(:certificate_orders).each do |child_folder|
-
certificate_orders = child_folder.certificate_orders.count
-
contents << child_folder.id if certificate_orders > 0
-
@total_certificate_orders +=certificate_orders
-
end
-
else
-
contents << self.id
-
@total_certificate_orders +=self.certificate_orders.count
-
end
-
contents.join(',')
-
end
-
1
memoize :folder_contents
-
-
1
def can_destroy?
-
99
!archived? && !expired? && !active? && !revoked?
-
end
-
-
1
def self.reset_to_system_folders(team,options={})
-
if team
-
co_list = team.certificate_orders.joins{signed_certificates.outer}
-
folders = team.folders
-
expired_folder = options[:expired_folder] || folders.find_by(expired: true)
-
revoked_folder = options[:revoked_folder] || folders.find_by(revoked: true)
-
active_folder = options[:active_folder] || folders.find_by(active: true)
-
default_folder = options[:default_folder] || folders.find_by(default: true)
-
-
if expired_folder
-
co_list.expired.where{(folder_id != expired_folder.id) | (folder_id == nil)}.update_all(folder_id: expired_folder.id)
-
end
-
if revoked_folder
-
co_list.revoked.where{(folder_id != revoked_folder.id) | (folder_id == nil)}.update_all(folder_id: revoked_folder.id)
-
end
-
if default_folder
-
co_list.unused_credits.where{(folder_id != default_folder.id) | (folder_id == nil)}.update_all(folder_id: default_folder.id)
-
end
-
if active_folder
-
co_list.where{id <<
-
(co_list.expired.ids + co_list.revoked.ids + co_list.unused_credits.ids).flatten.compact.uniq
-
}.update_all(folder_id: active_folder.id)
-
end
-
end
-
end
-
-
1
protected
-
-
# if this is going to be the default folder, all others should not
-
1
def there_can_only_be_one_default_folder
-
495
if self.destroyed?
-
# create a new default folder if default is destroyed
-
if default
-
new_default = ssl_account.folders.create(default: true, name: 'default')
-
if new_default.persisted?
-
ssl_account.update_column(:default_folder_id, new_default.id)
-
end
-
end
-
else
-
# If this is the default folder and saved normally, make sure there are no other defaults
-
495
if default && can_destroy?
-
99
ssl_account.folders.where.not(id: id)
-
.where(default: true).update_all(default: false)
-
99
ssl_account.update_column(:default_folder_id, id)
-
end
-
end
-
end
-
-
1
def release_certificate_orders
-
certificate_orders.update_all(folder_id: nil)
-
end
-
end
-
1
class FundedAccount < ActiveRecord::Base
-
1
using_access_control
-
1
belongs_to :ssl_account
-
-
1
money :amount, :currency => false
-
-
1
validates_presence_of :ssl_account
-
-
1
attr_accessor :funding_source, :order_type, :deduct_order, :target_amount, :discount_amount
-
-
1
serialize :card_declined
-
-
1
after_initialize do
-
99
self.deduct_order ||= false if new_record?
-
end
-
-
1
NEW_CREDIT_CARD = "new credit card"
-
1
PAYPAL = "paypal"
-
-
1
def deduct_order?
-
["true", true].include? @deduct_order
-
end
-
-
1
def add_cents(cents)
-
FundedAccount.update_counters id, cents: cents
-
end
-
-
1
def card_recently_declined?
-
card_declined && card_declined[:declined_at] &&
-
card_declined[:declined_at].is_a?(DateTime) &&
-
card_declined[:declined_at] > 1.hour.ago
-
end
-
-
1
def delay_transaction
-
return false unless card_recently_declined?
-
if card_recently_declined?
-
cards = card_declined[:cards]
-
max = cards && cards.any? && cards.count >= 5 && cards.uniq.count == 1
-
user = User.unscoped.find card_declined[:user_id]
-
update(card_declined: card_declined.merge(next_attempt:
-
card_declined[:declined_at] + (max ? 1.minute : 30.seconds)
-
)
-
)
-
if max
-
SystemAudit.create(
-
owner: user,
-
target: self,
-
action: "Transaction declines have reached maximum limit of 5 attempts. #{card_declined[:controller]}",
-
notes: "Card ending in ##{cards.last} was declined 5 times in the last hour. User #{user.login} from team #{ssl_account.get_team_name}."
-
)
-
end
-
end
-
end
-
end
-
class Helpers
-
include Singleton
-
include ActionView::Helpers::TextHelper
-
include ActionView::Helpers::UrlHelper
-
include ActionView::Helpers::DateHelper
-
include ActionView::Helpers::TagHelper
-
include ActionView::Helpers::NumberHelper
-
end
-
class IndividualValidation < Contact
-
validates :user_id, presence: true
-
end
-
class InvalidApiCertificateRequest < CaApiRequest
-
end
-
class InvalidApiDcvEmails < CaApiRequest
-
end
-
class InvalidApiSslManagerRequest < CaApiRequest
-
end
-
class InvalidApiUserRequest < CaApiRequest
-
end
-
class Invoice < ActiveRecord::Base
-
include Filterable
-
include Sortable
-
-
belongs_to :billable, polymorphic: true
-
belongs_to :payment, -> { unscope(where: :state) }, class_name: 'Order', foreign_key: :order_id
-
has_many :orders, -> { unscope(where: :state) }, foreign_key: :invoice_id
-
-
attr_accessor :credit_reason
-
-
PAYMENT_METHODS = {bp: 'billing_profile', wire: 'wire_transfer', po: 'po_other'}
-
PAYMENT_METHODS_TEXT = {bp: 'Billing Profile', wire: 'WireXfer', po: 'PO/Other'}
-
STATUS = %w{pending paid refunded partially_refunded archived}
-
DEFAULT_STATUS = STATUS.dup - ['archived']
-
-
before_validation :set_duration, on: :create, if: :payable_invoice?
-
before_validation :set_status, on: :create, if: :payable_invoice?
-
before_validation :set_default_billing, if: :payable_invoice?
-
before_validation :set_address, if: :payable_invoice?
-
after_create :generate_reference_number, if: :payable_invoice?
-
after_create :notify_admin_billing, if: :payable_invoice?
-
-
validates :first_name, :last_name, :address_1, :country, :city,
-
:state, :postal_code, presence: true, unless: :payable_invoice?
-
-
def self.index_filter(params)
-
filters = {}
-
p = params
-
filters[:status] = { 'in' => p[:status] } unless p[:status].blank?
-
filters[:reference_number] = { 'LIKE' => p[:reference_number] } unless p[:reference_number].blank?
-
-
unless p[:start_date_type].blank? || p[:start_date].blank?
-
operator = COMPARISON[p[:start_date_type].to_sym]
-
filters[:start_date] = { operator => DateTime.parse(p[:start_date]).beginning_of_day }
-
end
-
-
unless p[:end_date_type].blank? || p[:end_date].blank?
-
operator = COMPARISON[p[:end_date_type].to_sym]
-
filters[:end_date] = { operator => DateTime.parse(p[:end_date]).end_of_day }
-
end
-
t = p[:team]
-
if t.present?
-
found = SslAccount.where(
-
"ssl_slug = ? OR acct_number = ? OR id = ? OR company_name = ?", t, t, t, t
-
)
-
filters[:billable_id] = { '=' => found.first.id } if found.any?
-
end
-
result = filter(filters)
-
result = result.where("orders.reference_number" => p[:order_ref]) if p[:order_ref].present?
-
result
-
end
-
-
def self.get_invoices_for_select(ssl_account)
-
ssl_acct = Invoice.get_team ssl_account
-
ssl_acct.invoices
-
.map{|mi| ["#{mi.reference_number.upcase} (#{mi.status.gsub('_', ' ')})", mi.reference_number]}
-
.insert(0, ['NEW INVOICE', 'new_invoice'])
-
end
-
-
def self.get_current_invoice(ssl_account)
-
if ssl_account.billing_monthly?
-
MonthlyInvoice.get_current_invoice ssl_account
-
else
-
DailyInvoice.get_current_invoice ssl_account
-
end
-
end
-
-
def self.create_invoice_for_team(ssl_account)
-
ssl_acct = Invoice.get_team ssl_account
-
attrs = { billable_id: ssl_acct.id, billable_type: 'SslAccount' }
-
ssl_acct.billing_monthly? ? MonthlyInvoice.create(attrs) : DailyInvoice.create(attrs)
-
end
-
-
def self.invoice_exists_for_team?(ssl_account)
-
ssl_acct = Invoice.get_team ssl_account
-
if ssl_account.billing_monthly?
-
MonthlyInvoice.invoice_exists? ssl_acct
-
else
-
DailyInvoice.invoice_exists? ssl_acct
-
end
-
end
-
-
def self.get_or_create_for_team(ssl_account)
-
ssl_acct = Invoice.get_team ssl_account
-
if Invoice.invoice_exists_for_team?(ssl_acct)
-
Invoice.get_current_invoice ssl_acct
-
else
-
Invoice.create_invoice_for_team ssl_acct
-
end
-
end
-
-
def archived?
-
status == 'archived'
-
end
-
-
def paid_wire_transfer?
-
payment && payment.notes.include?(PAYMENT_METHODS_TEXT[:wire])
-
end
-
-
def paid_po_other?
-
payment && payment.notes.include?(PAYMENT_METHODS_TEXT[:po])
-
end
-
-
def paid?
-
status == 'paid'
-
end
-
-
def pending?
-
status == 'pending'
-
end
-
-
def refunded?
-
status == 'refunded'
-
end
-
-
def partially_refunded?
-
status == 'partially_refunded'
-
end
-
-
def show_payment_actions?
-
amt = get_amount
-
amt = amt.is_a?(Integer) ? amt : amt.cents
-
!(paid? || refunded? || partially_refunded? || (amt == 0))
-
end
-
-
def show_refund_actions?
-
payment && !(merchant_refunded? || refunded?)
-
end
-
-
def max_credit
-
amt = if payment && !refunded?
-
refunds = get_merchant_refunds
-
return 0.0 if (refunds == payment.amount) && (payment.get_funded_account_amount == 0)
-
-
if payment.get_merchant == 'other'
-
payment.get_funded_account_amount - refunds
-
else
-
(payment.make_available_total) - refunds
-
end
-
else
-
0.0
-
end
-
Money.new(amt)
-
end
-
-
def merchant_refunded?
-
fully_refunded = false
-
if payment
-
ref_merchant = payment.get_merchant
-
if ref_merchant && %{stripe paypal authnet}.include?(ref_merchant)
-
order_amount = payment.get_total_merchant_amount
-
fully_refunded = (order_amount - get_merchant_refunds) == 0
-
end
-
end
-
fully_refunded
-
end
-
-
def archive!
-
update(status: 'archived')
-
end
-
-
def full_refund!
-
update(status: 'refunded')
-
end
-
-
def partial_refund!
-
update(status: 'partially_refunded')
-
end
-
-
def get_type_format
-
type.gsub('Invoice', '')
-
end
-
-
def get_approved_items
-
orders.where(approval: 'approved')
-
end
-
-
def get_removed_items
-
orders.where(approval: 'rejected')
-
end
-
-
def get_credited_total
-
if refunded? &&
-
( (payment.make_available_total - get_merchant_refunds) > get_cents )
-
get_amount
-
else
-
max_credit
-
end
-
end
-
-
def get_merchant_refunds
-
payment.refunds.any? ? payment.refunds.pluck(:amount).sum : 0
-
end
-
-
def get_cents
-
get_approved_items.map(&:cents).sum
-
end
-
-
def get_amount
-
get_approved_items.map(&:amount).sum
-
end
-
-
def get_paid_invoice_amount
-
Money.new(payment.cents + payment.get_funded_account_amount)
-
end
-
-
def get_amount_format
-
amt = get_amount
-
amt.is_a?(Fixnum) ? Money.new(get_cents).format : amt.format
-
end
-
-
def get_final_amount
-
if %w{paypal stripe authnet}.include?(payment.get_merchant)
-
payment.get_total_merchant_amount
-
else
-
get_cents - payment.get_funded_account_amount - get_voided_cents
-
end
-
end
-
-
def get_voided_cents
-
get_approved_items.where(
-
state: %w{fully_refunded partially_refunded}
-
).uniq.pluck(:cents).sum
-
end
-
-
def funded_account_credit?
-
payment.get_funded_account_amount > 0
-
end
-
-
def get_final_amount_format
-
Money.new(get_final_amount).format
-
end
-
-
def get_item_descriptions
-
orders.inject({}) do |final, o|
-
co = o.certificate_orders.first
-
domains = o.get_reprocess_domains
-
desc = if o.invoice_description.blank?
-
"Additional #{domains[:non_wildcard]} non-wildcard and #{domains[:wildcard]} wildcard domains for certificate order ##{co.ref}."
-
else
-
"#{o.invoice_description} For certificate order ##{co.ref}."
-
end
-
-
final[o.reference_number] = {
-
description: desc,
-
item: co.respond_to?(:description_with_tier) ? co.description_with_tier(o) : co.certificate.description['certificate_type'],
-
new_domains: domains[:new_domains_count],
-
wildcard: domains[:wildcard],
-
non_wildcard: domains[:non_wildcard]
-
}
-
final
-
end
-
end
-
-
def invoice_bill_to_str
-
target = get_any_address
-
-
if target.is_a?(BillingProfile) || (target.payable_invoice? && !address_blank?)
-
addr = []
-
addr << target.company unless target.company.blank?
-
addr << "#{target.first_name} #{target.last_name}"
-
addr << target.address_1
-
addr << target.address_2 unless target.address_2.blank?
-
addr << [target.city, target.state, target.postal_code].compact.join(', ')
-
addr << target.country
-
addr
-
else
-
[]
-
end
-
end
-
-
def payable_invoice?
-
monthly_invoice? || daily_invoice?
-
end
-
-
def monthly_invoice?
-
is_a?(MonthlyInvoice) || type == 'MonthlyInvoice'
-
end
-
-
def daily_invoice?
-
is_a?(DailyInvoice) || type == 'DailyInvoice'
-
end
-
-
def notify_invoice_paid(user=nil)
-
Assignment.users_can_manage_invoice(billable).each do |u|
-
OrderNotifier.payable_invoice_paid(
-
user: u, invoice: self, paid_by: user
-
).deliver_now
-
end
-
end
-
-
private
-
-
def fix_missing_certificate_order
-
o=Order.where(invoice_id: self.id)
-
missing=o.find_all{|order|order.certificate_orders.empty?}.last
-
co=CertificateOrder.find_by_ref("ref from the notes in missing")
-
missing.line_items.last.update_columns sellable_type: "CertificateOrder", sellable_id: co.id
-
end
-
-
def self.get_team(ssl_account)
-
ssl_account.is_a?(Integer) ? SslAccount.find(ssl_account) : ssl_account
-
end
-
-
# IF team has billing profiles, retreive address from "default" profile
-
# IF default profile is NOT set, then use last created profile address
-
def get_any_address
-
profiles = billable.billing_profiles
-
default = profiles.any? ? profiles.where(default_profile: true) : []
-
last_profile = (profiles.any? && default.any?) ? default.first : nil
-
last_profile = profiles.order(created_at: :desc).first unless last_profile
-
(address_blank? && !last_profile.nil?) ? last_profile : self
-
end
-
-
def address_blank?
-
address_1.blank? &&
-
country.blank? &&
-
city.blank? &&
-
state.blank? &&
-
postal_code.blank?
-
end
-
-
def generate_reference_number
-
if reference_number.blank?
-
last_invoice = if monthly_invoice?
-
MonthlyInvoice.last_invoice_for_month(billable.id, self)
-
else
-
DailyInvoice.last_invoice_for_day(billable.id, self)
-
end
-
-
ref_parts = last_invoice.reference_number.split('-') if last_invoice
-
ref = if last_invoice && ref_parts.count == 4
-
sub_ref = ref_parts.pop.to_i + 1
-
ref_parts.push(sub_ref)
-
ref_parts.join('-')
-
elsif last_invoice && ref_parts.count == 3
-
"#{last_invoice.reference_number}-1"
-
else
-
"#{monthly_invoice? ? 'mi' : 'di'}-#{SecureRandom.hex(2)}-#{Time.now.to_i.to_s(32)}"
-
end
-
-
update_attribute(:reference_number, ref)
-
end
-
end
-
-
def notify_admin_billing
-
Assignment.users_can_manage_invoice(billable).each do |u|
-
OrderNotifier.payable_invoice_new(user: u, invoice: self).deliver_now
-
end if Settings.invoice_notify
-
end
-
-
def set_address
-
if address_blank?
-
target = get_any_address
-
if target.is_a?(BillingProfile)
-
self.company = target.company
-
self.first_name = target.first_name
-
self.last_name = target.last_name
-
self.address_1 = target.address_1
-
self.address_2 = target.address_2
-
self.city = target.city
-
self.state = target.state
-
self.postal_code = target.postal_code
-
self.country = target.country
-
end
-
end
-
end
-
-
def set_duration
-
self.start_date = monthly_invoice? ? MonthlyInvoice::START_DATE : DailyInvoice::START_DATE
-
self.end_date = monthly_invoice? ? MonthlyInvoice::END_DATE : DailyInvoice::END_DATE
-
end
-
-
def set_status
-
self.status = 'pending' if status.blank?
-
end
-
-
def set_default_billing
-
self.default_payment = PAYMENT_METHODS[:bp] if default_payment.blank?
-
end
-
end
-
# for EV, this refers to Jurisdiction of Incorporation.
-
# (see https://sslcomapi.docs.apiary.io/#reference/ssl-certificates/ssl-certificates-collection/create-an-ssl-certificate)
-
-
class Joi < Contact
-
-
belongs_to :ssl_account
-
-
BUSINESS_CATEGORY = {b: "Private Organization", c: "Government Entity", d: "Business Entity", e: "Non-Commercial Entity"}
-
-
validates :city, :state, :country, :incorporation_date, :assumed_name, presence: true
-
validates :business_category, presence: true,
-
inclusion: {in: BUSINESS_CATEGORY.values,
-
message: "needs to one of the following: #{BUSINESS_CATEGORY.values.join(', ')}"}
-
-
end
-
class LegacyV2UserMapping < ActiveRecord::Base
-
belongs_to :user_mappable, :polymorphic => true
-
-
def customer
-
OldSite::Customer.unscoped.find self.old_user_id
-
end
-
end
-
class LineItem < ActiveRecord::Base
-
belongs_to :order, touch: true
-
belongs_to :affiliate
-
belongs_to :sellable, :polymorphic => true
-
-
money :amount
-
-
# set #amount when adding sellable. This method is aliased to <tt>sellable=</tt>.
-
def sellable_with_price=(sellable)
-
self.amount = sellable && sellable.price ? sellable.price : 0
-
self.sellable_without_price = sellable
-
end
-
alias_method_chain :sellable=, :price
-
-
def initialize(*params)
-
super(*params)
-
self.affiliate_payout_rate ||= 0.0
-
end
-
-
def sellable_unscoped
-
if sellable_type == 'CertificateOrder'
-
CertificateOrder.unscoped.find_by_id(sellable_id)
-
else
-
sellable
-
end
-
end
-
-
def affiliate_commission
-
Money.new(affiliate_commission_price)
-
end
-
-
def affiliate_commission_price
-
(affiliate and not affiliate_payout_rate.blank?) ?
-
affiliate_payout_rate*amount.cents : 0
-
end
-
-
def studio_fee
-
Money.new(studio_fee_rate*amount.cents)
-
end
-
-
def studio_payout
-
Money.new((1-studio_fee_rate)*amount.cents)
-
end
-
-
def net_profit
-
Money.new(net_profit_price)
-
end
-
-
def net_profit_price
-
amount.cents-(affiliate_payout_rate*amount.cents)
-
end
-
end
-
require 'open-uri'
-
require 'digest/sha1'
-
-
class LocalFile < ::Tempfile
-
# The filename, *not* including the path, of the "uploaded" file
-
attr_reader :original_filename
-
-
def initialize(path, file_name = File.basename(path), tmpdir = Dir::tmpdir)
-
raise "#{path} file does not exist" unless File.exist?(path)
-
#content_type ||= @@image_mime_types[File.extname(path)]
-
#raise "Unrecognized MIME type for #{path}" unless content_type
-
#@content_type = content_type
-
@original_filename = file_name
-
super Digest::SHA1.hexdigest(path), tmpdir
-
#@tempfile = Tempfile.new(@original_filename)
-
FileUtils.copy_file(path, self.path)
-
end
-
-
alias local_path path
-
-
def method_missing(method_name, *args, &block) #:nodoc:
-
@tempfile.send(method_name, *args, &block)
-
end
-
-
def original_filename
-
@original_filename
-
end
-
-
def content_type
-
mime = `file --mime -br #{self.path}`.strip
-
mime = mime.gsub(/\A.*: */,"")
-
mime = mime.gsub(/;.*\z/,"")
-
mime = mime.gsub(/,.*\z/,"")
-
mime
-
end
-
end
-
class LockedRecipient < Contact
-
validates :user_id, presence: true
-
-
def self.create_for_co(co, target_assignee=nil)
-
assignee = target_assignee.nil? ? co.assignee : User.find(target_assignee)
-
locked_recipient = co.locked_recipient
-
co.reload
-
if assignee
-
iv = co.ssl_account.individual_validations.find_by(user_id: assignee.id)
-
params = {
-
first_name: iv ? iv.first_name : assignee.first_name,
-
last_name: iv ? iv.last_name : assignee.last_name,
-
email: assignee.email,
-
user_id: assignee.id,
-
contactable_type: co.class,
-
contactable_id: co.id,
-
parent_id: iv ? iv.id : nil,
-
status: (iv ? Contact::statuses[iv.status] : Contact::statuses[:in_progress])
-
}
-
temp_lr = LockedRecipient.new(params)
-
lr = temp_lr if locked_recipient.nil? && temp_lr.save
-
-
-
if target_assignee && locked_recipient
-
lr = locked_recipient.update(params)
-
lr = co.locked_recipient
-
end
-
-
if lr.persisted? && iv && iv.validation_histories.any?
-
lr.validation_histories << iv.validation_histories
-
end
-
end
-
lr
-
end
-
end
-
1
class LockedRegistrant < Registrant
-
1
serialize :domains
-
1
alias_attribute :constraints, :domains
-
end
-
class ManagedCertificate < SignedCertificate
-
# will_paginate
-
cattr_accessor :per_page
-
@@per_page = 10
-
end
-
class ManagedCsr < Csr
-
belongs_to :ssl_account
-
has_many :certificate_order_managed_csrs, dependent: :destroy
-
end
-
class ManagedUser < User
-
self.table_name = 'users'
-
-
end
-
class MonthlyInvoice < Invoice
-
-
START_DATE = DateTime.now.beginning_of_month
-
END_DATE = DateTime.now.end_of_month
-
-
validates :start_date, :end_date, :status, :billable_id, :billable_type, :default_payment, presence: true
-
-
def self.invoice_exists?(ssl_account)
-
ssl = Invoice.get_team ssl_account
-
ssl && ssl.monthly_invoices
-
.where(start_date: START_DATE, status: 'pending').any?
-
end
-
-
def self.get_current_invoice(ssl_account)
-
ssl = Invoice.get_team ssl_account
-
if ssl
-
ssl.monthly_invoices.order(created_at: :desc)
-
.where(start_date: START_DATE, status: 'pending').first
-
else
-
nil
-
end
-
end
-
-
def self.last_invoice_for_month(ssl_account, exclude=nil)
-
ssl = Invoice.get_team ssl_account
-
ssl.monthly_invoices.order(id: :desc)
-
.where(start_date: START_DATE).where.not(id: exclude).first
-
end
-
end
-
class Note < ActiveRecord::Base
-
-
include ActsAsNotable::Note
-
-
belongs_to :notable, :polymorphic => true
-
-
default_scope{ order("created_at asc")}
-
-
# NOTE: install the acts_as_votable plugin if you
-
# want user to vote on the quality of notes.
-
#acts_as_voteable
-
-
# NOTE: Notes belong to a user
-
belongs_to :user
-
-
end
-
class NotificationGroup < ActiveRecord::Base
-
belongs_to :ssl_account
-
-
has_many :notification_groups_contacts, dependent: :destroy
-
has_many :contacts, through: :notification_groups_contacts,
-
source: :contactable, source_type: 'Contact'
-
-
has_many :notification_groups_subjects, dependent: :destroy
-
has_many :certificate_orders, through: :notification_groups_subjects,
-
source: :subjectable, source_type: 'CertificateOrder'
-
has_many :certificate_contents, through: :notification_groups_subjects,
-
source: :subjectable, source_type: 'CertificateContent'
-
has_many :certificate_names, through: :notification_groups_subjects,
-
source: :subjectable, source_type: 'CertificateName'
-
has_many :schedules
-
has_many :scan_logs
-
-
attr_accessor :ssl_client
-
-
preference :notification_group_triggers, :string
-
-
# validates :friendly_name, allow_nil: false, allow_blank: false,
-
# length: { minimum: 1, maximum: 255 }
-
-
before_create do |ng|
-
ng.ref = 'ng-' + SecureRandom.hex(1) + Time.now.to_i.to_s(32)
-
ng.friendly_name = ng.ref if ng.friendly_name.blank?
-
end
-
-
# will_paginate
-
cattr_accessor :per_page
-
@@per_page = 10
-
-
def to_param
-
ref
-
end
-
-
def self.auto_manage_email_address(cc, cud, contacts=[])
-
notification_groups = cc.certificate_order.notification_groups
-
-
if notification_groups
-
notification_groups.each do |group|
-
ngc = group.notification_groups_contacts
-
-
contacts.each do |contact|
-
if cud == 'delete'
-
ngc.where(contactable_id: contact.id, email_address: nil).destroy_all
-
ngc.where(contactable_id: contact.id).update_all(contactable_type: nil, contactable_id: nil)
-
elsif cud == 'update'
-
ngc.where(["contactable_id = ? and email_address IS NOT ?",
-
contact.id,
-
nil]).update_all(email_address: contact.email)
-
end
-
end
-
end
-
end
-
end
-
-
def self.auto_manage_cert_name(cc, cud, domain=nil)
-
notification_groups = cc.certificate_order.notification_groups
-
-
if notification_groups
-
notification_groups.includes(:notification_groups_subjects).each do |group|
-
ngs = group.notification_groups_subjects
-
-
if domain
-
if cud == 'delete'
-
ngs.where(subjectable_type: 'CertificateName', subjectable_id: domain.id, domain_name: nil).delete_all
-
ngs.where(subjectable_type: 'CertificateName', subjectable_id: domain.id)
-
.update_all(subjectable_type: nil, subjectable_id: nil)
-
elsif cud == 'update'
-
ngs.where([
-
"subjectable_type = ? and subjectable_id = ? and domain_name IS NOT ?",
-
"CertificateName",
-
domain.id,
-
nil
-
]).update_all(domain_name: domain.name)
-
end
-
else
-
cc.certificate_names.includes(:notification_groups_subjects).each do |cn|
-
if cud == 'create'
-
cn.notification_groups_subjects.create(notification_group_id: group.id) if cn.notification_groups_subjects.
-
empty?{|s|s.notification_group_id==group.id}
-
elsif cud == 'delete'
-
ngs.where(subjectable_type: 'CertificateName', subjectable_id: cn.id, domain_name: nil).delete_all
-
ngs.where(subjectable_type: 'CertificateName', subjectable_id: domain.id)
-
.update_all(subjectable_type: nil, subjectable_id: nil)
-
end
-
end
-
end
-
end
-
end
-
end
-
-
# def signed_certificates
-
# certificate_orders.
-
# map(&:certificate_contents).flatten.compact.
-
# map(&:csr).flatten.compact.
-
# map(&:signed_certificates)
-
# end
-
#
-
# def unique_signed_certificates
-
# ([]).tap do |result|
-
# tmp_certs={}
-
# signed_certificates.flatten.compact.each do |sc|
-
# if tmp_certs[sc.common_name]
-
# tmp_certs[sc.common_name] << sc
-
# else
-
# tmp_certs.merge! sc.common_name => [sc]
-
# end
-
# end
-
#
-
# tmp_certs
-
# tmp_certs.each do |k, v|
-
# result << tmp_certs[k].max{ |a, b| a.expiration_date <=> b.expiration_date }
-
# end
-
# end
-
# end
-
#
-
# def unrenewed_signed_certificates
-
# unique_signed_certificates.select{ |sc| sc.certificate_order.renewal.blank? }
-
# end
-
#
-
# def renewed?(sc, renew_date)
-
# eds = SignedCertificate.where(:common_name=>sc.common_name).
-
# map(&:expiration_date).compact.sort
-
# eds.detect do |ed|
-
# ed > renew_date.days.from_now
-
# end
-
# end
-
#
-
# def expiring_certificates_in_group
-
# results = []
-
# exp_dates = ReminderTrigger.all.map do |rt|
-
# preferred_notification_group_triggers(rt).to_i
-
# end.sort{ |a, b| b <=> a}
-
#
-
# unrenewed_signed_certificates.compact.each do |sc|
-
# sed = sc.expiration_date
-
# unless sed.blank?
-
# exp_dates.each_with_index do |ed, i|
-
# if (i < exp_dates.count - 1) && (sed < ed.to_i.days.from_now) && (sed >= exp_dates[i + 1].days.from_now)
-
# results << Struct::Notification.new(ed, exp_dates[i + 1], sc) unless
-
# renewed?(sc, exp_dates.first.to_i)
-
# end
-
# end
-
# end
-
# end
-
# results
-
# end
-
#
-
# def expired_certificates_in_group(intervals, years_back = 1)
-
# year_in_days = 365
-
# (Array.new(intervals.count){ |i| i = [] }).tap do |results|
-
# unrenewed_signed_certificates.compact.each do |sc|
-
# sed = sc.expiration_date
-
# unless sed.blank?
-
# years_back.times do |i|
-
# years = year_in_days * (i + 1)
-
# adj_int = intervals.map{ |idx| idx + years }
-
# adj_int.each_with_index do |ed, interval|
-
# if (interval < adj_int.count - 1) && (sed < ed.to_i.days.ago) && (sed >= adj_int[interval + 1].days.ago)
-
# results[interval] << Struct::Notification.new(ed, adj_int[interval + 1], sc) unless
-
# renewed?(sc, intervals.last)
-
# break
-
# end
-
# end
-
# end
-
# end
-
# end
-
# end
-
# end
-
#
-
# def send_and_create_reminders(expired_certs, digest, past = false, interval = nil)
-
# expired_certs.each do |ec|
-
# except_list = %w(
-
# hepsi danskhosting webcruit
-
# epsa\.com\.co
-
# magicexterminating suburbanexterminating)
-
# except_certs = ->(domain, exempt){
-
# exempt.find do |e|
-
# domain=~eval("/#{e}/")
-
# end
-
# }
-
#
-
# cert = ec.cert
-
# contact_ids = cert.certificate_order.certificate_contents.flatten.compact
-
# .map(&:certificate_contacts).flatten.compact.map(&:id)
-
# sltd_contact_ids = notification_groups_contacts.where.not(contactable_id: nil).pluck(:contactable_id).uniq
-
# sltd_contact_ids &= contact_ids
-
#
-
# contacts = Contact.where(id: sltd_contact_ids).pluck(:first_name, :last_name, :email).
-
# concat(notification_groups_contacts.where(contactable_id: nil)
-
# .pluck(:contactable_type, :contactable_type, :email_address).uniq).uniq
-
#
-
# contacts.uniq.compact.each do |contact|
-
# unless SentReminder.exists?(trigger_value: [ec.before, ec.after].join(', '),
-
# expires_at: cert.expiration_date,
-
# subject: cert.common_name,
-
# recipients: contact[2]) || except_certs.(cert.common_name, except_list)
-
# d_key = contact.join(', ')
-
# if digest[d_key].blank?
-
# digest.merge!({ d_key => [ec] })
-
# else
-
# digest[d_key] << ec
-
# end
-
# end
-
# end
-
# end
-
#
-
# unless digest.empty?
-
# digest.each do |d|
-
# u_certs = d[1].map(&:cert).map(&:common_name).uniq.compact
-
# begin
-
# unless u_certs.empty?
-
# logger.info "Sending reminder"
-
# body = past ? Reminder.past_expired_digest_notice(d, interval) :
-
# Reminder.digest_notice(d)
-
# body.deliver unless body.to.empty?
-
# end
-
#
-
# d[1].each do |ec|
-
# logger.info "create SentReminder"
-
# SentReminder.create(trigger_value: [ec.before, ec.after].join(", "),
-
# expires_at: ec.cert.expiration_date,
-
# signed_certificate_id: ec.cert.id,
-
# subject: ec.cert.common_name,
-
# body: body,
-
# recipients: d[0].split(",").last)
-
# end
-
# rescue Exception=>e
-
# logger.error e.backtrace.inspect
-
# raise e
-
# end
-
# end
-
# end
-
# end
-
#
-
# def self.scan_notification_group(group)
-
# certs = group.expiring_certificates_in_group
-
# digest = {}
-
# group.send_and_create_reminders(certs, digest)
-
#
-
# digest.clear
-
# intervals = [-30, -7, 16, 31]
-
# certs = group.expired_certificates_in_group(intervals).flatten.compact
-
# group.send_and_create_reminders(certs, digest, true, intervals)
-
# end
-
-
def scan_notification_group
-
exp_dates = ReminderTrigger.all.map do |rt|
-
preferred_notification_group_triggers(rt).to_i
-
end.sort{ |a, b| b <=> a}
-
-
except_list = %w(
-
hepsi danskhosting webcruit
-
epsa\.com\.co
-
magicexterminating suburbanexterminating)
-
except_certs = ->(domain, exempt){
-
exempt.find do |e|
-
domain=~eval("/#{e}/")
-
end
-
}
-
-
results = []
-
contacts = []
-
contacts.concat notification_groups_contacts.where(["email_address IS NOT ? and contactable_id IS ?",
-
nil,
-
nil]).pluck(:email_address)
-
contacts.concat Contact.where(id: notification_groups_contacts.where(contactable_type: 'CertificateContact')
-
.pluck(:contactable_id)).pluck(:email)
-
-
domains = []
-
domains.concat notification_groups_subjects.where(["domain_name IS NOT ? and subjectable_id IS ?",
-
nil,
-
nil]).pluck(:domain_name)
-
domains.concat CertificateName.where(id: notification_groups_subjects.where(subjectable_type: 'CertificateName')
-
.pluck(:subjectable_id)).pluck(:name)
-
-
last_group_number = scan_logs.maximum('scan_group')
-
domains.uniq.each do |domain|
-
unless except_certs.(domain, except_list)
-
scan_status = 'expiring'
-
expiration_date = nil
-
ssl_domain_connect(domain.gsub("*.", "www."), scan_port)
-
-
if ssl_client
-
cert = domain_certificate
-
# expiration_date = cert.not_after unless cert.blank?
-
scanned_cert = ScannedCertificate.create_with(
-
body: cert.to_s,
-
decoded:cert.to_text
-
).find_or_create_by(
-
serial: cert.serial.to_s
-
)
-
expiration_date = cert.blank? ? nil : cert.not_after
-
-
if expiration_date
-
exp_dates.each_with_index do |ed, i|
-
if (i < exp_dates.count - 1) &&
-
(expiration_date < ed.to_i.days.from_now) &&
-
(expiration_date >= exp_dates[i + 1].days.from_now) &&
-
(expiration_date >= DateTime.now.to_date)
-
results << Struct::Notification.new(ed, exp_dates[i + 1],
-
domain, expiration_date, scan_status, scanned_cert.id)
-
end
-
end
-
end
-
-
if ssl_client.verify_result == '27'
-
scan_status = 'untrusted'
-
elsif expiration_date && expiration_date < DateTime.now.to_date
-
scan_status = 'expired'
-
elsif !cert.subject_alternative_names.include? domain
-
scan_status = 'name_mismatch'
-
end
-
-
if notify_all.nil? && scan_status != 'expiring'
-
results << Struct::Notification.new(nil, nil, domain, expiration_date, scan_status, scanned_cert.id)
-
end
-
ssl_client.close
-
else
-
scan_status = 'not_found'
-
scanned_cert = nil
-
-
if notify_all.nil?
-
results << Struct::Notification.new(nil, nil, domain, nil, scan_status, scanned_cert)
-
end
-
end
-
-
scan_logs.create(
-
scanned_certificate: scanned_cert,
-
domain_name: domain,
-
scan_status: scan_status,
-
expiration_date: expiration_date,
-
scan_group: last_group_number ? (last_group_number + 1) : 1
-
)
-
end
-
end
-
-
unless results.empty? or contacts.empty?
-
results.each do |result|
-
unless SentReminder.exists?(trigger_value: [result.before, result.after].join(", "),
-
expires_at: result.expire,
-
subject: result.domain,
-
recipients: contacts.uniq.join(";"),
-
reminder_type: result.reminder_type)
-
logger.info "Sending reminder"
-
d = [",," + contacts.uniq.join(";")]
-
body = Reminder.domain_digest_notice(d, result, self)
-
body.deliver unless body.to.empty?
-
logger.info "create SentReminder"
-
SentReminder.create(trigger_value: [result.before, result.after].join(", "),
-
expires_at: result.expire,
-
subject: result.domain,
-
body: body,
-
recipients: contacts.uniq.join(";"),
-
reminder_type: result.reminder_type)
-
end
-
end
-
end
-
end
-
-
def ssl_domain_connect(url, default_port,timeout=3)
-
context = OpenSSL::SSL::SSLContext.new
-
Timeout.timeout(timeout) do
-
domain, ori_port = url.split ":"
-
tcp_client = TCPSocket.new(domain, ori_port || default_port)
-
self.ssl_client = OpenSSL::SSL::SSLSocket.new tcp_client, context
-
self.ssl_client.hostname = domain
-
self.ssl_client.sync_close=true
-
self.ssl_client.connect
-
end
-
rescue
-
self.ssl_client = nil
-
end
-
-
def domain_certificate
-
certs = ssl_client.peer_cert_chain_with_openssl_extension
-
unless certs.blank?
-
certs.first
-
end
-
end
-
-
# Scan the domains belongs to notification groups and sending a reminder if expiration date is in reminder days what has been set"
-
def self.scan(options={})
-
Sandbox.find_by_host(options[:db]).use_database unless options[:db].blank?
-
current = DateTime.now
-
month = current.strftime("%m").to_i.to_s
-
day = current.strftime("%d").to_i.to_s
-
week_day = current.strftime("%w")
-
hour = current.strftime("%H").to_i.to_s
-
minute = current.strftime("%M").to_i.to_s
-
-
NotificationGroup.includes(:schedules).find_each do |group|
-
schedules = {}
-
group.schedules.each do |arr|
-
if schedules[arr.schedule_type].blank?
-
schedules[arr.schedule_type] = arr.schedule_value
-
else
-
schedules[arr.schedule_type] = (schedules[arr.schedule_type] + '|' + arr.schedule_value.to_s).split('|').sort.join('|')
-
end
-
end
-
-
run_scan = true
-
if schedules['Simple']
-
if (schedules['Simple'] == '1' && minute != '0') ||
-
(schedules['Simple'] == '2' && hour != '0' && minute != '0') ||
-
(schedules['Simple'] == '3' && week_day != '0' && hour != '0' && minute != '0') ||
-
(schedules['Simple'] == '4' && day != '1' && week_day != '0' && hour != '0' && minute != '0') ||
-
(schedules['Simple'] == '5' && month != '1' && day != '1' && week_day != '0' && hour != '0' && minute != '0')
-
run_scan = false
-
end
-
else
-
if schedules['Hour']
-
run_scan = (schedules['Hour'] == 'All' || schedules['Hour'].split('|').include?(hour))
-
else
-
run_scan = (hour == '0') unless schedules['Minute']
-
end
-
-
if run_scan && schedules['Minute']
-
run_scan = (schedules['Minute'] == 'All' || schedules['Minute'].split('|').include?(minute))
-
elsif run_scan && !schedules['Minute']
-
run_scan = (minute == '0')
-
end
-
-
if run_scan
-
run_scan_week_day = false
-
if schedules['Weekday']
-
run_scan_week_day = (schedules['Weekday'] == 'All' || schedules['Weekday'].split('|').include?(week_day))
-
end
-
-
unless run_scan_week_day
-
if schedules['Month']
-
run_scan = (schedules['Month'] == 'All' || schedules['Month'].split('|').include?(month))
-
end
-
-
if run_scan && schedules['Day']
-
run_scan = (schedules['Day'] == 'All' || schedules['Day'].split('|').include?(day))
-
elsif run_scan && !schedules['Day']
-
run_scan = (day == '1') unless schedules['Hour'] && schedules['Minute']
-
end
-
end
-
end
-
end
-
group.scan_notification_group if run_scan && !group.status
-
end
-
end
-
-
def set_schedule_to_daily_scan
-
schedules.create(schedule_type: 'Simple', schedule_value: 2) if schedules.blank?
-
# current_schedules = schedules.pluck(:schedule_type)
-
# if current_schedules.include? 'Simple'
-
# schedules.last.update_attribute(:schedule_value, 2) unless schedules.last.schedule_value == 2
-
# else
-
# schedules.destroy_all
-
# schedules.build(schedule_type: 'Simple', schedule_value: 2).save
-
# end
-
end
-
end
-
class NotificationGroupsContact < ActiveRecord::Base
-
belongs_to :notification_group
-
belongs_to :contactable, polymorphic: true
-
end
-
class NotificationGroupsSubject < ActiveRecord::Base
-
belongs_to :notification_group
-
belongs_to :subjectable, polymorphic: true
-
end
-
class Oauth2Token < AccessToken
-
attr_accessor :state
-
def as_json(options={})
-
d = {:access_token=>token, :token_type => 'bearer'}
-
d[:expires_in] = expires_in if expires_at
-
d
-
end
-
-
def to_query
-
q = "access_token=#{token}&token_type=bearer"
-
q << "&state=#{URI.escape(state)}" if @state
-
q << "&expires_in=#{expires_in}" if expires_at
-
q << "&scope=#{URI.escape(scope)}" if scope
-
q
-
end
-
-
def expires_in
-
expires_at.to_i - Time.now.to_i
-
end
-
end
-
class Oauth2Verifier < OauthToken
-
validates_presence_of :user
-
attr_accessor :state
-
-
def exchange!(params={})
-
OauthToken.transaction do
-
token = Oauth2Token.create! :user=>user,:client_application=>client_application, :scope => scope
-
invalidate!
-
token
-
end
-
end
-
-
def code
-
token
-
end
-
-
def redirect_url
-
callback_url
-
end
-
-
def to_query
-
q = "code=#{token}"
-
q << "&state=#{URI.escape(state)}" if @state
-
q
-
end
-
-
protected
-
-
def generate_keys
-
self.token = OAuth::Helper.generate_key(20)[0,20]
-
self.expires_at = 10.minutes.from_now
-
self.authorized_at = Time.now
-
end
-
-
end
-
# Simple store of nonces. The OAuth Spec requires that any given pair of nonce and timestamps are unique.
-
# Thus you can use the same nonce with a different timestamp and viceversa.
-
class OauthNonce < ActiveRecord::Base
-
validates_presence_of :nonce, :timestamp
-
validates_uniqueness_of :nonce, :scope => :timestamp
-
-
# Remembers a nonce and it's associated timestamp. It returns false if it has already been used
-
def self.remember(nonce, timestamp)
-
oauth_nonce = OauthNonce.create(:nonce => nonce, :timestamp => timestamp)
-
return false if oauth_nonce.new_record?
-
oauth_nonce
-
end
-
end
-
class OauthToken < ActiveRecord::Base
-
belongs_to :client_application
-
belongs_to :user
-
validates_uniqueness_of :token
-
validates_presence_of :client_application, :token
-
before_validation :generate_keys, :on => :create
-
-
def invalidated?
-
invalidated_at != nil
-
end
-
-
def invalidate!
-
update_attribute(:invalidated_at, Time.now)
-
end
-
-
def authorized?
-
authorized_at != nil && !invalidated?
-
end
-
-
def to_query
-
"oauth_token=#{token}&oauth_token_secret=#{secret}"
-
end
-
-
protected
-
-
def generate_keys
-
self.token = OAuth::Helper.generate_key(40)[0,40]
-
self.secret = OAuth::Helper.generate_key(40)[0,40]
-
end
-
end
-
module OldSite
-
def self.quit?
-
begin
-
# See if a 'Q' has been typed yet
-
while c = STDIN.read_nonblock(1)
-
puts "Q pressed"
-
return true if c == 'Q'
-
end
-
# No 'Q' found
-
false
-
rescue Errno::EINTR
-
false
-
rescue Errno::EAGAIN
-
# nothing was ready to be read
-
false
-
rescue EOFError
-
# quit on the end of the input stream
-
# (user hit CTRL-D)
-
true
-
end
-
end
-
-
def self.detect_abort
-
abort('Exit: user terminated') if quit?
-
end
-
-
def self.initialize
-
tables=%w(Customer Order Certificate OrderNumber Merchant MerchantContact
-
OrdersShoppingCart)
-
tables.each do |t|
-
tc = ('OldSite::'+t).constantize
-
source_tables=V2MigrationProgress.all.select {|p|
-
p.source_table_name==tc.table_name} || []
-
#if the number of records on the source table has change, then migrate
-
#those records again
-
unless tc.count==source_tables.count
-
source_tables.each {|sc|sc.delete}
-
tc.find_each do |o|
-
V2MigrationProgress.create(:source_table_name=>tc.table_name,
-
:source_id=>o.source_obj_id)
-
end
-
end
-
end
-
end
-
-
#this function is preferable to initialize because it does not delete existing
-
#records and instead just adds new ones
-
def self.dynamic_initialize
-
tables=%w(Customer Order Certificate OrderNumber Merchant MerchantContact
-
OrdersShoppingCart)
-
V2MigrationProgress.remove_migratable_orphans
-
tables.each do |t|
-
OldSite.detect_abort
-
ap "looking for new records for #{t}"
-
tc = ('OldSite::'+t).constantize
-
V2MigrationProgress.remove_legacy_orphans(tc)
-
source_tables=V2MigrationProgress.select(:source_id).where(:source_table_name.eq => tc.table_name) || []
-
#if the number of records on the source table has change, then add the new
-
#records
-
unless tc.count==source_tables.count
-
legacy_ids=tc.source_ids
-
ap ["legacy count: #{tc.count.to_s}", "migration progress count: #{source_tables.count.to_s}"].join(", ")
-
missing = legacy_ids-source_tables.map(&:source_id)
-
tc.where(tc.primary_key.to_sym + missing).each do |o|
-
ap "creating V2MigrationProgress for #{tc.table_name+'_'+o.send(tc.primary_key).to_s}"
-
V2MigrationProgress.create(:source_table_name=>tc.table_name,
-
:source_id=>o.source_obj_id)
-
end
-
else
-
ap "no new records found for #{t}"
-
end
-
end
-
end
-
-
# this is the main function to do the migration
-
def self.migrate_all
-
Authorization.ignore_access_control(true)
-
ActiveRecord::Base.logger.level = 3 # at any time
-
ap "Usage: type 'Q' and press Enter to exit this program"
-
dynamic_initialize
-
Customer.migrate_all
-
Order.migrate_all
-
Customer.sync_attributes_with_v2
-
::DuplicateV2User.make_latest_login_primary
-
Certificate.sync_certs
-
#verify all LineItems have a sellable or else delete them
-
LineItem.all.each{|l|l.destroy if l.sellable.blank?}
-
self.adjust_site_seals_workflow
-
self.adjust_certificate_order_prepaid
-
self.adjust_certificate_content_workflow
-
end
-
-
def self.certs_and_line_items_mismatch
-
ActiveRecord::Base.logger.level = 3 # at any time
-
i=0
-
OldSite::Order.find_each(:include=>{:order_number=>
-
[{:certificates=>{:certificate_product=>:product}},
-
:orders_shopping_carts]}) do |o|
-
ids=[]
-
o.order_number.orders_shopping_carts.each do |osc|
-
ids<<osc.order_number.certificates.map(&:product).map(&:ProductID)
-
end
-
if ids.uniq.count>1
-
p 'Error! '+o.OrderNumber
-
logger.error 'Certificate products mismatch for order: '+o.OrderNumber
-
else
-
p [ids, "count: #{i+=1}, OrderID: #{o.OrderNumber}"]
-
end
-
end
-
end
-
-
#just a one-time-use convenience method. The logic fix was incorporated into
-
#the migration script
-
def self.adjust_user_profile_info
-
OldSite::Customer.find_each do |c|
-
u=V2MigrationProgress.find_by_source(c).migratable
-
(u.updated_at=c.updated_at
-
u.first_name= c.FirstName
-
u.last_name = c.LastName
-
u.update_record_without_timestamping) unless u.blank?
-
end
-
end
-
-
#just a one-time-use convenience method. The logic fix was incorporated into
-
#the migration script
-
def self.adjust_order_payment_method
-
ActiveRecord::Base.logger.level = 3 # at any time
-
::Order.find_each do |o|
-
old_o=V2MigrationProgress.find_by_migratable_and_source_table_name(o,
-
"Orders", :first)
-
unless old_o.blank?
-
old_o.source_obj.copy_payment_method_to(o)
-
o.save
-
end
-
end
-
end
-
-
#just a one-time-use convenience method. Just trying to import skipped
-
#signed certificates
-
def self.import_signed_certificates
-
Authorization.ignore_access_control(true)
-
ActiveRecord::Base.logger.level = 3 # at any time
-
i=0
-
count = ::Csr.count
-
::Csr.find_each do |c|
-
cert = c.certificate_content.try(:migrated_from)
-
cert = cert.last unless cert.blank?
-
unless cert.blank?
-
p ["#{i+=1} of #{count}, CertificateID: #{cert.CertificateID}"]
-
if c.signed_certificate.blank? && !cert.SignedCert.blank?
-
c.signed_certificate_by_text=cert.SignedCert
-
if c.signed_certificate
-
c.signed_certificate.update_attribute(:created_at,
-
cert.ReadyNoticeSentToCustomer)
-
c.certificate_content.workflow_state='issued'
-
else
-
c.certificate_content.workflow_state='csr_submitted'
-
msg="Error: Could not import signed certificate
-
from Old::Certificate#{cert.CertificateID}"
-
logger.error msg
-
p msg
-
end
-
c.save
-
end
-
end
-
end
-
end
-
-
#just a one-time-use convenience method. The logic fix was incorporated into
-
#the migration script
-
def self.adjust_signed_certificate_created_at
-
SignedCertificate.find_each do |sc|
-
sc.update_attribute :created_at, sc.csr.certificate_content.created_at
-
end
-
end
-
-
#just a one-time-use convenience method. The logic fix was incorporated into
-
#the migration script
-
def self.adjust_server_type
-
::CertificateContent.find_each do |cc|
-
if cc.server_software.blank?
-
unless V2MigrationProgress.find_by_migratable(cc).blank?
-
c=V2MigrationProgress.find_by_migratable(cc).source_obj
-
cc.created_at=c.SubmitDate
-
cc.server_software=OldSite::ServerType.server_software(
-
c.ServerType)
-
cc.save(false)
-
end
-
end
-
end
-
end
-
-
#just a one-time-use convenience method. The logic fix was incorporated into
-
#the migration script
-
def self.adjust_line_items
-
Authorization.ignore_access_control(true)
-
CertificateOrder.find_each do |co|
-
if co.order
-
oscs=V2MigrationProgress.find_by_migratable co.order, :all
-
unless oscs.empty?
-
o=oscs.find{|osc|osc.source_obj.is_a? OrdersShoppingCart}.source_obj
-
if o
-
items=o.orders_kit_carts.each_with_object([]) do |okc, arry|
-
arry << okc.KitItemName
-
end
-
co.v2_line_items=items unless items.empty?
-
co.line_item_qty=1
-
co.save
-
end
-
end
-
end
-
end
-
end
-
-
#one time function to correct misplaced v2_migration_progress from users to duplicate_v2_users
-
def self.update_v2_migrations_for_duplicate_users
-
migs = DuplicateV2User.all
-
created = migs.map(&:created_at)
-
dups=[]
-
dup_tmp=created.each{|c|dups<<c if created.count(c) > 1} #find duplicates
-
dup_created_at=migs.select{|c|c.created_at==dup_tmp[0]}
-
migs-=dup_created_at
-
migs_h = Hash[migs.map{|m|[m.created_at.to_s, m]}] #hash migrated dups using created_at.to_s as key
-
oc=OldSite::Customer.select("CustomerID, CreatedOn")
-
oc_h=Hash[oc.map{|o|[o.CreatedOn.to_s, o]}] #hash legacy users using CreatedOn.to_s as key
-
migs_h.merge!(oc_h){|key, old, new|[new, old]}
-
non_matched=migs_h.select{|k,v|!v.is_a?(Array)}
-
non_matched.each{|k,v|migs_h.delete(k)}
-
migs_h.each do |k,v|
-
mp=v[0].v2_migration_progress
-
mp.migratable=v[1]
-
mp.save
-
end
-
end
-
-
#DEPRECATED - see OldSite::Customer.sync_attributes_with_v2
-
#user changes such as passwords or emails (or even logins) are sync using this method
-
def self.sync_changed_users
-
d = DuplicateV2User.all
-
v2_users = V2MigrationProgress.where(:migratable_type =~ "User").map(&:migratable).uniq
-
#get all migrated users into array
-
migs=d+v2_users
-
created = migs.map(&:created_at)
-
dups=[]
-
dup_tmp=created.each{|c|dups<<c if created.count(c) > 1} #find duplicates
-
dup_created_at=migs.select{|c|c.created_at==dup_tmp[0]}
-
migs-=dup_created_at
-
migs_h = Hash[migs.map{|m|[m.created_at.to_s, m]}] #hash migrated users/dups using created_at.to_s as key
-
oc=OldSite::Customer.select("Email, UserName, Password, CreatedOn")
-
oc_h=Hash[oc.map{|o|[o.CreatedOn.to_s, o]}] #hash legacy users using CreatedOn.to_s as key
-
migs_h.merge!(oc_h){|key, old, new|[new, old]}
-
non_matched=migs_h.select{|k,v|!v.is_a?(Array)}
-
non_matched.each{|k,v|migs_h.delete(k)}
-
changed=migs_h.select do |k,v|
-
v[1].email!=v[0].Email || (v[1].is_a?(User) ? v[1].crypted_password : v[1].password)!=v[0].Password ||
-
v[1].login!=v[0].UserName
-
end
-
msgs=[]
-
changed.each do |k,v|
-
msgs<< "changes detected for #{v[1].model_and_id}"
-
if v[1].email!=v[0].Email
-
msgs<< "email changed from #{v[1].email} to #{v[0].Email}"
-
v[1].update_attribute :email, v[0].Email
-
end
-
if (v[1].is_a?(User) ? v[1].crypted_password : v[1].password)!=v[0].Password
-
msgs<< "password changed from #{v[1].is_a?(User) ? v[1].crypted_password : v[1].password} to #{v[0].Password}"
-
v[1].update_attribute (v[1].is_a?(User) ? :crypted_password : :password), v[0].Password
-
end
-
if v[1].login!=v[0].UserName
-
msgs<< "login changed from #{v[1].login} to #{v[0].UserName}"
-
v[1].update_attribute :login, v[0].UserName
-
end
-
end
-
ap msgs
-
#oc_created_at=oc.map(&:CreatedOn)
-
#oc_s=oc_created_at.sort.map(&:to_s)
-
#ca_s=created.sort.map(&:to_s)
-
#diff_s=oc_s-ca_s
-
end
-
-
def self.sync_duplicate_v2_user_attributes
-
DuplicateV2User.sync_mismatched_attributes if DuplicateV2User.mismatched_attributes.blank?
-
if DuplicateV2User.mismatched_attributes.blank?
-
"successfully synced DuplicateV2User attributes"
-
else
-
"failed syncing DuplicateV2User attributes"
-
end
-
end
-
-
def self.adjust_certificate_content_workflow
-
CertificateContent.find_each(:include=>
-
[:registrant,:certificate_contacts, {:csr=>:signed_certificates}]) do |cc|
-
if V2MigrationProgress.find_by_migratable_id_and_migratable_type cc.id,
-
'CertificateContent'
-
csr = cc.csr
-
cert = csr.try(:signed_certificate)
-
registrant = cc.registrant
-
contacts = cc.certificate_contacts
-
if cert
-
cc.update_attribute :workflow_state, 'issued'
-
elsif !contacts.empty?
-
cc.update_attribute :workflow_state, 'contacts_provided'
-
elsif registrant
-
cc.update_attribute :workflow_state, 'info_provided'
-
elsif csr
-
cc.update_attribute :workflow_state, 'csr_submitted'
-
else
-
cc.update_attribute :workflow_state, 'new'
-
end
-
end
-
end
-
end
-
-
def self.adjust_certificate_order_prepaid
-
CertificateOrder.find_each(:include=>[:orders, :certificate_contents]) do |co|
-
if co.order.try("preferred_migrated_from_v2?")
-
if co.workflow_state=='paid' && co.certificate_content.blank?
-
co.preferred_payment_order = 'prepaid'
-
co.save
-
end
-
end
-
end
-
end
-
-
def self.adjust_site_seals_workflow
-
SiteSeal.find_each(:include=>
-
{:certificate_orders=>[:certificate_contents, :orders]}) do |ss|
-
unless ss.certificate_order.blank? || ss.certificate_order.order.blank?
-
state = ss.certificate_order.certificate_content.workflow_state if
-
ss.certificate_order && ss.certificate_order.certificate_content
-
case state
-
when 'issued'
-
ss.update_attribute :workflow_state,
-
SiteSeal::FULLY_ACTIVATED.to_s
-
when 'new'
-
ss.update_attribute :workflow_state, 'new'
-
else
-
ss.update_attribute :workflow_state,
-
SiteSeal::CONDITIONALLY_ACTIVATED.to_s
-
end
-
ss.update_seal_type
-
end
-
end
-
end
-
-
# we need to verify at the data level that migration integrity has been maintained
-
# compare non-duplicate user accounts and their orders and certificates
-
# then compare duplicates
-
def self.verify_migration_integrity
-
# for each v1 user, find the corresponding v2 user
-
# compare orders quantity and prices
-
# compare csrs and signed certificates (quantity and contents)
-
# we'll start off with non dupllicates and verify 1-to-1 mappings to orders
-
[].tap do |order_count_mismatch|
-
i=0
-
nd=OldSite::Customer.non_duplicates
-
p "total #{nd.count.to_s} legacy users to process"
-
nd.find_each do |c|
-
# need to get v2 user
-
p "processed #{i.to_s} legacy users" if i%100==0
-
user = c.migratable
-
if user.is_a?(User) && user.ssl_account
-
if user.ssl_account.cached_orders.count == c.orders.count
-
#user.ssl_account.orders.each do |o|
-
# o
-
#end
-
else
-
order_count_mismatch << user
-
p "#{user.login} (#{user.mode_and_id}) doesn't have the same number of orders as the legacy user"
-
end
-
end
-
i+=1
-
end
-
end
-
#OldSite::Customer.duplicates.find_each do |c|
-
# # need to get v2 user
-
# user = c.migratable.class == User ? c.migratable : c.migratable.user
-
# user.ssl_account.orders.count >= c.orders.count
-
#end
-
end
-
-
class Base < ActiveRecord::Base
-
establish_connection :ssl_store_mssql
-
self.abstract_class=true
-
-
def self.source_ids
-
key = self.primary_key.to_sym
-
select(key).map(&key)
-
end
-
-
def source_obj_id
-
send(self.class.primary_key)
-
end
-
-
def v2_migration_progress
-
V2MigrationProgress.find_by_source self
-
end
-
-
def migratable
-
v2_migration_progress.migratable
-
end
-
-
def self.v2_migration_progresses
-
V2MigrationProgress.find_all_by_source_table_name(table_name)
-
end
-
-
def self.unmigrated_records
-
ids = source_ids
-
vids=V2MigrationProgress.select(:source_id).
-
where((:source_table_name =~ table_name) & ((:migrated_at ^ nil) |
-
(:migratable_type ^ nil))).map(&:source_id)
-
unmigrated = ids-vids
-
ap ["all #{self.class.to_s} objs: "+ids.count.to_s, "migrated: "+vids.count.to_s,
-
"remaining: "+unmigrated.count.to_s].join(', ')
-
[where(primary_key.to_sym + unmigrated), unmigrated.count]
-
end
-
-
def migratable_exists?
-
vmp=V2MigrationProgress.includes(:migratable).find_by_source(self)
-
vmp && vmp.migrated_at && vmp.migratable
-
end
-
-
def record_migration_progress(p=nil)
-
mp = V2MigrationProgress.includes(:migratable).find_by_old_object(self)
-
if mp.blank?
-
msg="Error: V2MigrationProgress record is blank for #{self.model_and_id}"
-
logger.error(msg)
-
ap msg
-
elsif mp.migrated_at.blank? || mp.migratable.blank?
-
begin
-
migratable=p ? migrate(p) : migrate
-
rescue Exception=>e
-
msg="Error in #{self.model_and_id}#{' for '+p.model_and_id if p && !p.is_a?(Hash)} : #{e.message}"
-
logger.error(msg)
-
ap msg
-
ap e.backtrace.inspect
-
raise e
-
end
-
mp.update_attributes :migrated_at=>Time.new,
-
:migratable=>(migratable)
-
migratable
-
else
-
logger.error "Error!: Already migrated #{self.id}"
-
mp.migratable
-
end
-
end
-
-
def copy_attributes(corresponding)
-
self.class::ATTR_MAP.each do |k,v|
-
corresponding.send(k.to_s+"=", (k!=:country ? self.send(v) : OldSite::MerchantContact.convert_country(self.send(v))))
-
end
-
end
-
-
def unmatched_attributes(corresponding)
-
attrs=self.class::ATTR_MAP.select do |k,v|
-
corresponding.send(k) != (k!=:country ? self.send(v) : OldSite::MerchantContact.convert_country(self.send(v)))
-
end
-
end
-
-
def sync_unmatched_attributes(corresponding)
-
attrs=self.class::ATTR_MAP.each do |k,v|
-
val=(k!=:country ? self.send(v) : OldSite::MerchantContact.convert_country(self.send(v)))
-
if corresponding.send(k) != val
-
corresponding.update_attribute k, val
-
end
-
end
-
end
-
-
def sync_unmatched_attributes_for_migratable
-
migratable_tmp=V2MigrationProgress.find_by_old_object(self).migratable
-
sync_unmatched_attributes(migratable_tmp) if migratable_tmp
-
end
-
-
def unmatched_attributes_for_migratable
-
migratable_tmp=V2MigrationProgress.find_by_old_object(self).migratable
-
unmatched_attributes(migratable_tmp) if migratable_tmp
-
end
-
-
def self.verification_report
-
unmatched, no_migratable = [], []
-
find_each do |r|
-
attrs=r.unmatched_attributes_for_migratable
-
if attrs
-
unless attrs.empty?
-
unmatched << r.id
-
#ap "unmatched attributes #{attrs.to_s} found for #{r.model_and_id}"
-
end
-
else
-
no_migratable<<r.id
-
#ap "migratable no found for #{r.model_and_id}"
-
end
-
end
-
ap "unmatched attributes found for the following #{base_class.to_s}: #{unmatched}"
-
ap "no migratables found for the following #{base_class.to_s}: #{no_migratable}"
-
[unmatched, no_migratable]
-
end
-
end
-
-
class Customer < Base
-
set_table_name 'Customer'
-
set_primary_key 'CustomerID'
-
has_many :orders, :class_name=>'OldSite::Order', :foreign_key=>'CustomerID'
-
has_many :certificates, :through=>:orders
-
has_many :merchants, :class_name=>'OldSite::Merchant',
-
:foreign_key=>'CustomerID'
-
has_many :billing_addresses, :class_name=>'OldSite::Address',
-
:foreign_key=>'CustomerID'
-
has_many :orders_kit_carts, :class_name=>'OldSite::OrdersKitCart',
-
:foreign_key=>'CustomerID'
-
has_many :kit_carts, :class_name=>'OldSite::KitCart',
-
:foreign_key=>'CustomerID'
-
has_many :addresses, :class_name=>'OldSite::Address',
-
:foreign_key=>'CustomerID'
-
belongs_to :company, :class_name=>'OldSite::Company',
-
:foreign_key=>'CompanyID'
-
alias_attribute :id, :CustomerID
-
alias_attribute :login, :UserName
-
alias_attribute :email, :Email
-
alias_attribute :crypted_password, :Password
-
alias_attribute :created_at, :CreatedOn
-
alias_attribute :updated_at, :LastUpdated
-
attr_accessor :status
-
-
after_initialize do
-
if new_record?
-
self.status ||= "enabled"
-
end
-
end
-
-
def self.invalid_accounts
-
[].tap do |ia|
-
unscoped.select([primary_key, "Email", "UserName"]).find_each do |c|
-
ia << c if (c.Email.length < 6) || (c.UserName.length < 3) ||
-
(c.Email !~ Authlogic::Regex.email) || (c.UserName !~ Authlogic::Regex.login)
-
end
-
end
-
end
-
-
INVALID_ACCOUNTS ||= OldSite::Customer.invalid_accounts
-
-
default_scope{ where(primary_key.to_sym - OldSite::Customer::INVALID_ACCOUNTS.map(&:CustomerID))}
-
-
def self.pk_sym
-
primary_key.to_sym
-
end
-
-
def migrate
-
lu = LegacyV2UserMapping.create(:old_user_id=>self.id)
-
u = User.find_by_login(self.login) || User.find_by_email(self.email)
-
if u
-
du=DuplicateV2User.create(:user=>u, :login=>self.login,
-
:email=>self.email, :password=>self.crypted_password, :created_at=>
-
self.created_at, :updated_at=>self.updated_at)
-
du.legacy_v2_user_mappings << lu
-
ap "created DuplicateV2User #{du.model_and_id}"
-
else
-
u = User.new
-
props = %w(id login email crypted_password created_at
-
updated_at status)
-
props.each do |p|
-
u.send(p+'=', self.send(p))
-
end
-
u.first_name = self.FirstName
-
u.last_name = self.LastName
-
u.active=true
-
u.roles << Role.find_by_name(Role::CUSTOMER)
-
u.create_ssl_account
-
u.legacy_v2_user_mappings << lu
-
if u.save
-
ap "created #{u.model_and_id}"
-
else
-
ap "failed! #{u.model_and_id} not saved: #{u.errors.full_messages.join(", ")}"
-
end
-
end
-
du || u
-
end
-
-
# def migrate_from_old
-
# lu = LegacyV2UserMapping.create(:old_user_id=>self.id)
-
# u = User.find_by_login(self.login) || User.find_by_email(self.email)
-
# if u
-
# sa=u.ssl_account
-
# du=DuplicateV2User.create(:user=>u, :login=>self.login,
-
# :email=>self.email, :password=>self.crypted_password, :created_at=>
-
# self.created_at)
-
# du.legacy_v2_user_mappings << lu
-
# else
-
# u = User.new
-
# props = %w(id login email crypted_password created_at status)
-
# props.each do |p|
-
# u.send(p+'=', self.send(p))
-
# end
-
# u.active=true
-
# u.roles << Role.find_by_name(Role::CUSTOMER)
-
# sa=u.create_ssl_account
-
# u.legacy_v2_user_mappings << lu
-
# u.save
-
# end
-
# self.orders.each do |order|
-
# #create order
-
# o = ::Order.create(:created_at=>order.OrderDate)
-
# o.billable=sa
-
# o.preferred_migrated_from_v2 = true
-
# o.cents=(order.OrderTotal*100).to_i
-
# o.currency="USD"
-
# order_num = order.order_number
-
# case order.PaymentMethod
-
# when "Request Quote"
-
# o.state="quote"
-
# when "Check", "Purchase Order", "Credit Card"
-
# o.state="paid"
-
# end
-
# #create order transaction
-
# ot=o.transactions.create(:created_at=>order.OrderDate)
-
# ot.amount=o.cents
-
# ot.success=true
-
# ot.message=order.AuthorizationResult
-
# ot.action="purchase"
-
# #create line_items
-
# order_num.orders_shopping_carts.each do |c|
-
# o.description=[o.description, c.OrderedProductDescription].join(': ')
-
# saved_qty = false
-
# c.Quantity.times do |i|
-
# co=CertificateOrder.new(:created_at=>order.OrderDate)
-
# co.sub_order_items << SubOrderItem.create(:product_variant_item=>
-
# ProductVariantItem.find_by_serial('mssl'))
-
# co.amount=(c.OrderedProductPrice*100).to_i/c.Quantity
-
# co.preferred_payment_order='prepaid' if c.certificates[i].blank? ||
-
# c.certificates[i].UnsignedCert.blank?
-
# #co.pay! true
-
# co.ssl_account=sa
-
# co.save
-
# li=o.line_items.create
-
# li.cents=(c.OrderedProductPrice*100).to_i
-
# li.sellable=co
-
# li.save
-
# #saving processed certs for paid only orders
-
# if o.state=="paid"
-
# unless c.certificates[i].blank?
-
# cert = c.certificates[i]
-
# cc=co.certificate_contents.create
-
# unless cert.UnsignedCert.blank?
-
# cc.signing_request=cert.UnsignedCert
-
# cc.created_at=cert.SubmitDate
-
# cc.server_software=OldSite::ServerType.server_software(
-
# cert.ServerType)
-
# cc.csr.signed_certificate_by_text=cert.SignedCert unless
-
# cert.SignedCert.blank?
-
# cc.save
-
# if m = cert.merchant
-
# r = m.copy_attributes_to cc.create_registrant
-
# r.save
-
# m.merchant_contacts.each do |mc|
-
# unless mc.MerchantID==0
-
# c_contact=cc.certificate_contacts.create
-
# mc.copy_attributes_to c_contact
-
# c_contact.save if c_contact.valid?
-
# end
-
# end
-
# end
-
# #36 certificates with unsignedcerts have no merchant
-
# end
-
# unless saved_qty
-
# #only one CertificateOrder needs to store qty info
-
# co.line_item_qty=c.Quantity
-
# saved_qty=true
-
# end
-
# end
-
# end
-
# end
-
# #disregard billing profiles
-
# #sa.billing_profiles << BillingProfile.new(order.billing_fields)
-
# end
-
# unless sa.orders<<o
-
# p order.OrderNumber
-
# raise ActiveRecord::Rollback, "Failed at OrderNumber #{order.
-
# OrderNumber}"
-
# end
-
# end
-
# end
-
-
def self.migrate_all
-
migrate_these = unmigrated_records
-
i=migrate_these[1]
-
unmigrated_records[0].find_each do |c|
-
#unmigrated_records[0].where(primary_key.to_sym - INVALID_ACCOUNTS.map(&pk_sym)).find_each do |c|
-
OldSite.detect_abort
-
i-=1
-
c.record_migration_progress unless c.migratable_exists?
-
ap "#{i} #{table_name} records remaining for migration"
-
end
-
V2MigrationProgress.status(self)
-
end
-
-
# find email addresses of v1 accounts that are duplicates
-
def self.duplicate_emails
-
all(:group=>'Email', :select=>'Email', :having=>'count(Email)>1')
-
end
-
-
# find logins of v1 accounts that are duplicates
-
def self.duplicate_logins
-
all(:group=>'UserName', :select=>'UserName',
-
:having=>'count(UserName)>1')
-
end
-
-
# find duplicate usernames based on v1 users with duplicate email addresses
-
def self.find_dup_email_and_username
-
names=duplicate_emails.map(&:email).map {|e|
-
OldSite::Customer.find_all_by_Email(e)}.map{|e| e.map(&:UserName)}
-
global_dup = []
-
names.each do |n|
-
g = names.pop
-
g.each do |m|
-
global_dup << m if names.flatten.include?(m)
-
end
-
end
-
global_dup
-
end
-
-
#these customers are not 'corrupted' with duplicate usernames or emails
-
def self.non_duplicates
-
de = duplicate_emails.map(&:Email)
-
dl = duplicate_logins.map(&:UserName)
-
where((:Email - de) & (:UserName - dl))
-
end
-
-
#these customers are 'corrupted' with either duplicate usernames or emails
-
def self.duplicates
-
de = duplicate_emails.map(&:Email)
-
dl = duplicate_logins.map(&:UserName)
-
where((:Email + de) | (:UserName + dl))
-
end
-
-
def self.unmigrate_all
-
Authorization.ignore_access_control(true)
-
OldSite::Customer.all.each {|c|
-
if User.exists?(c.id)
-
u=User.find(c.id)
-
u.ssl_account.destroy
-
end}
-
end
-
-
def self.sync_attributes_with_v2
-
count=0
-
select([:CustomerID, :UserName, :Email, :Password,
-
:CreatedOn, :LastUpdated]).find_in_batches do |customers|
-
l, e, p, c, u = 0,0,0,0,0
-
V2MigrationProgress.includes(:migratable).
-
where({:source_table_name=>"Customer"} & :source_id + customers.map(&:CustomerID)).each do |v|
-
o=customers.find{|c|c.CustomerID==v.source_id}
-
n=v.migratable
-
if n.login != o.UserName
-
p "changing username from #{n.login} to #{o.UserName}"
-
n.update_attribute(:login, o.UserName)
-
l+=1
-
end
-
if n.email != o.Email
-
p "changing email from #{n.email} to #{o.Email}"
-
n.update_attribute(:email, o.Email)
-
e+=1
-
end
-
if n.created_at.to_date != o.CreatedOn.to_date
-
p "changing created_at from #{n.created_at} to #{o.CreatedOn}"
-
n.update_attribute(:created_at, o.CreatedOn)
-
c+=1
-
end
-
if n.updated_at.to_date != o.LastUpdated.to_date
-
p "changing updated_at from #{n.updated_at} to #{o.LastUpdated}"
-
n.update_attribute(:updated_at, o.LastUpdated)
-
u+=1
-
end
-
if n.is_a? DuplicateV2User
-
if n.password != o.Password
-
p "changing password for duplicate user from #{n.password} to #{o.Password}"
-
n.update_attribute(:password, o.Password)
-
p+=1
-
end
-
else #assume User
-
if n.crypted_password != o.Password
-
p "changing password for user from #{n.crypted_password} to #{o.Password}"
-
n.update_attribute(:crypted_password, o.Password)
-
p+=1
-
end
-
end
-
end
-
count+=1
-
p "processed batch #{count} of 1000 records: \n
-
#{l} logins, #{e} emails, #{p} passwords, #{c} created_at, and #{u} updated_at synced"
-
end
-
end
-
end
-
-
class Certificate < OldSite::Base
-
set_table_name 'Certificate'
-
set_primary_key 'CertificateID'
-
belongs_to :order, :class_name=>'OldSite::Order', :foreign_key=>'OrderID'
-
belongs_to :certificate_product, :class_name=>
-
'OldSite::CertificateProduct', :foreign_key=>'CertificateProductID'
-
belongs_to :merchant, :class_name=>'OldSite::Merchant',
-
:foreign_key=>'MerchantID'
-
has_one :product, :through=>:certificate_product
-
alias_attribute :unsigned_cert, :UnsignedCert
-
-
HAS_SIGNED_BUT_NO_CSR=[13778, 17295]
-
-
default_scope{ where(:CertificateID - HAS_SIGNED_BUT_NO_CSR)}
-
-
def migrate(co)
-
co.certificate_contents.create.tap do |cc|
-
cc.created_at=self.SubmitDate
-
cc.server_software=OldSite::ServerType.server_software(
-
self.ServerType)
-
unless self.UnsignedCert.blank?
-
cc.signing_request=self.UnsignedCert
-
unless (self.SignedCert.blank? || cc.csr.blank?)
-
cc.csr.update_attribute(:created_at, self.SubmitDate)
-
cc.csr.signed_certificate_by_text=self.SignedCert
-
if cc.csr.signed_certificate
-
cc.csr.signed_certificate.update_attribute(:created_at,
-
self.ReadyNoticeSentToCustomer)
-
cc.workflow_state='issued'
-
else
-
cc.workflow_state='csr_submitted'
-
logger.error "Error: Could not import signed certificate
-
from Old::Certificate#{self.CertificateID}"
-
end
-
else
-
cc.workflow_state='csr_submitted'
-
end
-
cc.save
-
else
-
logger.error "Error! could not find csr for #{self.model_and_id}"
-
end
-
end
-
end
-
-
def migrate_cert_and_merchants(co)
-
cc=record_migration_progress(co) if V2MigrationProgress.
-
find_by_source(self).try(:migrated_at).blank?
-
if cc && !cc.new_record? && merchant
-
merchant.record_migration_progress(cc) if V2MigrationProgress.
-
find_by_source(merchant).try(:migrated_at).blank?
-
merchant.merchant_contacts.each do |mc|
-
mc.record_migration_progress(cc) if V2MigrationProgress.
-
find_by_source(mc).try(:migrated_at).blank?
-
end
-
end
-
#36 certificates with unsignedcerts have no merchant
-
end
-
-
# these signed certificates have not been migrated to v2
-
def self.unmigrated_signed_certificates
-
ncm=::SignedCertificate.select(:common_name).map(&:common_name).uniq
-
ocm=select(:CommonName).map(&:CommonName).uniq
-
diff=ocm-ncm
-
where(:CommonName + diff.compact.reject{|b|b==""})
-
end
-
-
def self.signed_certs_to_be_created
-
um=OldSite::Certificate.unmigrated_signed_certificates
-
umm=um.map{|u|V2MigrationProgress.find_by_source(u)}
-
nc=umm.map(&:migratable)
-
csrs=nc.csrs
-
csr_ids=csrs.compact.map(&:id)
-
bsc=SignedCertificate.where(:csr_id + csr_ids)
-
existing=bsc.map(&:csr_id)
-
csrs_without_signed_cert=csr_ids-existing
-
ap bsc.map(&:common_name)
-
end
-
-
def self.sync_certs
-
count=0
-
t_cc, t_cs, t_rc, t_csc, t_rsc = 0,[],[],[],[]
-
failed_cs, failed_rc, failed_csc, failed_rsc=[],[],[],[]
-
select([:CertificateID, :SubmitDate, :UnsignedCert, :CommonName,
-
:SignedCert, :ReadyNoticeSentToCustomer]).find_in_batches do |certs|
-
cc, cs, rc, csc, rsc = 0,[],[],[],[]
-
process_signed_cert=lambda do |n, o, counter, failed|
-
csr=n.csr
-
sc=csr.send "signed_certificate_by_text=", o.SignedCert
-
unless sc.blank? || sc.new_record?
-
p "successfully created #{sc.model_and_id} (#{sc.common_name})"
-
sc.update_attribute(:created_at, o.ReadyNoticeSentToCustomer)
-
n.workflow_state='issued'
-
counter<<sc.id
-
else
-
p "failed creating signed_certificate for #{csr.model_and_id} (#{csr.common_name})"
-
failed << csr.id
-
end
-
end
-
process_csr=lambda do |n, o, counter, failed|
-
n.reload.signing_request=o.UnsignedCert
-
csr=n.csr(true)
-
unless csr.blank? || csr.new_record?
-
p "successfully created #{csr.model_and_id} (#{csr.common_name})"
-
csr.update_attribute(:created_at, o.SubmitDate)
-
n.workflow_state='csr_submitted'
-
counter<<csr.id
-
if !o.SignedCert.blank?
-
if !csr.blank? && csr.signed_certificates.empty?
-
# need to create a signed_certificate
-
p "creating a signed_certificate for #{o.model_and_id}"
-
process_signed_cert.(n,o,csc,failed_csc)
-
elsif csr.signed_certificates.last.common_name.try(:downcase)!=o.CommonName.try(:downcase)
-
p "recreating #{csr.signed_certificates.last.model_and_id} for #{o.model_and_id}"
-
csr.signed_certificates.destroy_all
-
process_signed_cert.(n,o,rsc,failed_rsc)
-
end
-
end
-
else
-
p "failed creating csr for #{n.model_and_id}"
-
failed << n.id
-
end
-
n.save
-
end
-
V2MigrationProgress.includes(:migratable).
-
where({:source_table_name=>"Certificate"} & :source_id + certs.map(&:CertificateID)).each do |v|
-
o=certs.find{|c|c.CertificateID==v.source_id}
-
n=v.migratable
-
# verify a corresponding csr
-
if n.blank?
-
#need to refer to Order, maybe call OldSite::Order.migrate
-
p "certificate_content for #{o.model_and_id} doesn't exist, maybe had data integrity issues?"
-
cc+=1
-
else
-
if !o.UnsignedCert.blank?
-
if n.csr.blank?
-
# need to create a csr
-
p "creating a csr for #{n.model_and_id}"
-
process_csr.(n,o,cs,failed_cs)
-
elsif n.csr.common_name.try(:downcase)!=o.CommonName.try(:downcase)
-
p "recreating #{n.csr.model_and_id} for #{o.model_and_id}"
-
n.csr.destroy
-
process_csr.(n,o,rc,failed_rc)
-
elsif !o.SignedCert.blank?
-
if n.csr.signed_certificates.empty?
-
# need to create a signed_certificate
-
p "creating a signed_certificate for #{o.model_and_id}"
-
process_signed_cert.(n,o,csc,failed_csc)
-
elsif n.csr.signed_certificates.last.common_name.try(:downcase)!=o.CommonName.try(:downcase)
-
p "recreating #{n.csr.signed_certificates.last.model_and_id} for #{o.model_and_id}"
-
n.csr.signed_certificates.destroy_all
-
process_signed_cert.(n,o,rsc,failed_rsc)
-
end
-
end
-
end
-
end
-
end
-
count+=1
-
t_cc, t_cs, t_rc, t_csc, t_rsc = t_cc+cc, t_cs+cs, t_rc+rc, t_csc+csc, t_rsc+rsc
-
p "processed batch #{count} of 1000 records: \n
-
#{cc} certificate_contents missing, #{cs.count} csrs created, #{rc.count} csrs recreated, #{csc.count} signed_certificates created,
-
#{rsc.count} signed_certificates recreated"
-
p "created csrs: #{cs.to_s}"
-
p "recreated csrs: #{rc.to_s}"
-
p "created signed_certificates: #{csc.to_s}"
-
p "recreated signed_certificates: #{rsc.to_s}"
-
p "failed creating csr for certificate_contents: #{failed_cs.to_s}"
-
p "failed recreating csr for certificate_contents: #{failed_rc.to_s}"
-
p "failed creating signed_certificates for csrs: #{failed_csc.to_s}"
-
p "failed recreating signed_certificates for csrs: #{failed_rsc.to_s}"
-
end
-
p "total: #{t_cc} certificate_contents missing, #{t_cs.count} csrs created, #{t_rc.count} csrs recreated,
-
#{t_csc.count} signed_certificates created, #{t_rsc.count} signed_certificates recreated"
-
p "failed creating csr for certificate_contents: #{failed_cs.to_s}"
-
p "failed recreating csr for certificate_contents: #{failed_rc.to_s}"
-
p "failed creating signed_certificates for csrs: #{failed_csc.to_s}"
-
p "failed recreating signed_certificates for csrs: #{failed_rsc.to_s}"
-
end
-
-
#somehow a few purchased credits appeared that do not belong a corresponding v2_migration_source
-
#we need to remove these to avoid paying for non existing credit on the old system
-
def self.orphaned_credits
-
CertificateOrder.unused_purchased_credits.
-
select{|co|co.certificate_content.v2_migration_sources.blank?}.
-
select{|b|b.ssl_account.primary_user.v2_migration_sources}
-
end
-
-
def self.unmigrated_old_certificates
-
ids=V2MigrationProgress.includes(:migratable).
-
where({:source_table_name=>"Certificate"}).select do |v|
-
v.migratable.blank?
-
end.map(&:source_id)
-
where(:CertificateID + ids)
-
end
-
-
def self.unmigrated_old_certificate_ids
-
ids=V2MigrationProgress.includes(:migratable).
-
where({:source_table_name=>"Certificate"}).select do |v|
-
v.migratable.blank?
-
end.map(&:source_id)
-
select(:CertificateID).where(:CertificateID + ids).map(&:CertificateID)
-
end
-
end
-
-
class Order < OldSite::Base
-
set_table_name 'Orders'
-
set_primary_key 'OrderNumber'
-
belongs_to :customer, :class_name=>'OldSite::Customer',
-
:foreign_key=>'CustomerID'
-
belongs_to :order_number, :class_name=>'OldSite::OrderNumber',
-
:foreign_key=>'OrderNumber'
-
has_many :certificates, :class_name=>'OldSite::Certificate',
-
:foreign_key=>'OrderID'
-
-
def user
-
V2MigrationProgress.find_by_old_object(customer).migratable unless
-
customer.blank?
-
end
-
-
def sa
-
user.instance_of?(User) ? user.ssl_account : user.user.ssl_account
-
end
-
-
def copy_payment_method_to(o)
-
case self.PaymentMethod
-
when /Request Quote/
-
o.state="quote"
-
o.quote_number=self.quoted_id
-
when /Check/, /Purchase Order/, /Credit Card/
-
o.state="paid"
-
o.po_number=self.PONumber if $&=="Purchase Order"
-
end
-
end
-
-
def migrate
-
unless user.blank?
-
#create order
-
msg="Creating Order for #{user.model_and_id} (#{sa.model_and_id})"
-
logger.error msg
-
ap msg
-
::Order.create(:created_at=>self.OrderDate).tap do |o|
-
o.billable=sa
-
o.preferred_migrated_from_v2 = true
-
o.cents=(self.OrderTotal*100).to_i
-
o.currency="USD"
-
self.copy_payment_method_to(o)
-
#create order transaction
-
ot=o.transactions.create(:created_at=>self.OrderDate)
-
ot.amount=o.cents
-
ot.success=true
-
ot.message=self.AuthorizationResult
-
ot.action="purchase"
-
unless ot.save
-
msg="Error! Could not save transaction #{ot.model_and_id} to #{o.model_and_id}"
-
logger.error msg
-
ap msg
-
else
-
msg="Saved transaction #{ot.model_and_id} to #{o.model_and_id}"
-
logger.error msg
-
ap msg
-
end
-
unless sa.orders<<o
-
msg="Error! Could not save order #{o.model_and_id} to #{sa.model_and_id}"
-
logger.error msg
-
ap msg
-
else
-
msg="Saved order #{o.model_and_id} to #{sa.model_and_id}"
-
logger.error msg
-
ap msg
-
end
-
end
-
else
-
msg="Skipping create Order for #{sa.model_and_id} since no user is found"
-
logger.error msg
-
ap msg
-
end
-
end
-
-
def migrate_orders_shopping_cart
-
order = V2MigrationProgress.find_by_old_object(self).migratable
-
unless order.blank?
-
ap "migrating legacy OrdersShoppingCart for Order.OrderNumber: #{self.OrderNumber}"
-
certs_created=false
-
order_number.orders_shopping_carts.each do |osc|
-
unless osc.migratable_exists?
-
ap "migrating #{osc.model_and_id}"
-
osc.record_migration_progress(:new_order=>order,
-
:certs_created=>certs_created)
-
certs_created=true
-
else
-
ap "skipping #{osc.model_and_id}, already exists"
-
end
-
end
-
else
-
msg = "Error! V2MigrationProgress#migratable for #{self.class.to_s}: #{self.id} not found"
-
logger.error msg
-
ap msg
-
end
-
end
-
-
def self.migrate_all
-
migrate_these = unmigrated_records
-
i=migrate_these[1]
-
ap "migrating #{i.to_s} #{table_name} records"
-
migrate_these[0].find_each(:include=>[{:order_number=>[:certificates,
-
{:orders_shopping_carts=>:orders_kit_carts}]}, :customer]) do |o|
-
OldSite.detect_abort
-
i-=1
-
unless o.migratable_exists?
-
#o.customer.blank? doesn't seem to use the default_scope{ of OldSite::Customer'}
-
if OldSite::Customer.exists? o.CustomerID
-
ap "migrating #{o.model_and_id}"
-
o.record_migration_progress
-
else
-
ap "skipping migration for #{o.model_and_id} because Customer not found or invalid"
-
ap "#{i} #{table_name} records remaining for migration"
-
next
-
end
-
else
-
ap "found and skipping migration for: #{o.model_and_id}"
-
end
-
o.migrate_orders_shopping_cart
-
ap "#{i} #{table_name} records remaining for migration"
-
end
-
V2MigrationProgress.status(self)
-
end
-
-
def self.extra_unpaid_certificate_orders
-
::Order.with_too_many_line_items.map(&:line_items).
-
flatten.uniq.map(&:sellable).uniq.map(&:certificate_contents).
-
flatten.uniq.select{|cc|cc.v2_migration_sources.blank?}
-
end
-
-
def map_card_type
-
case self.CardType
-
when "", nil
-
""
-
when "MasterCard"
-
"Master Card"
-
when "AMEX"
-
"American Express"
-
when "DISCOVER"
-
"Discover"
-
when "VISA"
-
"Visa"
-
end
-
end
-
-
#resuming migration that has been tested
-
def self.migrate_billing_profiles
-
::BillingProfile.password = "kama1jama1"
-
#find migrated orders that do not have a billing profile
-
oids=V2MigrationProgress.select("migratable_id").
-
where(:source_table_name >> "Orders", :migratable_type >> "Order").map(&:migratable_id)
-
queue = ::Order.select("id").where(:id + oids, :billing_profile_id >> nil,
-
:quote_number >> nil, :po_number >> nil)
-
queue_ids = queue.map(&:id)
-
v2=V2MigrationProgress.select("source_id, migratable_id").where(:source_table_name >> "Orders",
-
:migratable_type >> "Order", :migratable_id + queue_ids)
-
old_ids=v2.map(&:source_id)
-
select("OrderNumber, BillingLastName, BillingFirstName, BillingCompany, BillingAddress1, BillingAddress2,
-
BillingSuite, BillingCity, BillingState, BillingZip, BillingCountry, BillingPhone,
-
CardType,CardName,CardNumber,CardExtraCode,CardExpirationMonth,CardExpirationYear").
-
where(:OrderNumber + old_ids, :CardExpirationYear !~ "").order("OrderDate desc").each do |o|
-
#OldSite.detect_abort
-
cc_num=o.cc_num
-
newer=::Order.find_by_id(v2.find_by_source_id(o.OrderNumber).migratable_id)
-
unless cc_num.blank? || newer.billable.blank? || !newer.billing_profile.blank?
-
p "new==#{newer.id}, older==#{o.id}"
-
cvv=o.CardExtraCode.blank? ?
-
(ot=select("TransactionCommand").where(:OrderNumber >> o.OrderNumber).last
-
cvv_t=ot.cvv_code
-
cvv_t.blank? ? "na" : cvv_t) : o.CardExtraCode
-
attrs={
-
:ssl_account_id => newer.billable_id,
-
:description => o.CardName,
-
:first_name => o.BillingFirstName,
-
:last_name => o.BillingLastName,
-
:address_1 => [o.BillingAddress1,o.BillingSuite].join(", "),
-
:address_2 => o.BillingAddress2,
-
:country => o.BillingCountry,
-
:city => o.BillingCity,
-
:state => o.BillingState,
-
:postal_code => o.BillingZip.blank? ? "n/a" : o.BillingZip,
-
:phone => o.BillingPhone,
-
:company => o.BillingCompany,
-
:credit_card => o.map_card_type,
-
:card_number => cc_num,
-
:expiration_month => o.CardExpirationMonth,
-
:expiration_year => o.CardExpirationYear,
-
:security_code => cvv
-
}
-
Order.transaction do
-
p "migrating old Order billing profile #{o.OrderNumber}"
-
bp = BillingProfile.find_by_card_number_and_expiration_year(cc_num, o.CardExpirationYear.to_i) ||
-
BillingProfile.create(attrs)
-
if bp.valid?
-
p "billing_profile.id == "+bp.id.to_s
-
newer.billing_profile=bp
-
newer.save
-
else
-
p bp.errors
-
end
-
end
-
else
-
p "skipping old Order billing profile #{o.OrderNumber}"
-
end
-
end
-
end
-
-
#the only PaymentMethods are "Purchase Order", "Credit Card", "Request Quote", "", and "Check"
-
#cc_num only applies to "Credit Card"
-
def cc_num
-
plain_key="8773732869"
-
message = Base64.decode64 self.CardNumber
-
sha = Digest::SHA1.digest plain_key
-
key = sha[0..7]
-
iv = sha[8..15]
-
-
cipher = OpenSSL::Cipher::DES.new
-
cipher.decrypt # Call this before setting key or iv
-
cipher.key = key
-
cipher.iv = iv
-
ciphertext = cipher.update(message)
-
ciphertext << cipher.final
-
-
length=ciphertext[0..4].to_i
-
cc_number=ciphertext[5,length]
-
rescue
-
""
-
end
-
-
def cvv_code
-
self.TransactionCommand=~/x_card_code=(.+?)&/
-
$1
-
end
-
-
end
-
-
class OrdersShoppingCart < Base
-
set_table_name 'Orders_ShoppingCart'
-
set_primary_key 'Orders_ShoppingCartID'
-
# belongs_to :shopping_cart, :class_name=>'OldSite::ShoppingCart',
-
# :foreign_key=>'ShoppingCartRecID'
-
has_many :orders_kit_carts, :class_name=>'OldSite::OrdersKitCart',
-
:foreign_key=>'ShoppingCartRecID', :primary_key=>'ShoppingCartRecID'
-
belongs_to :order_number, :class_name=>'OldSite::OrderNumber',
-
:foreign_key=>'OrderNumber'
-
has_one :order, :through=>:order_number
-
belongs_to :product, :class_name=>'OldSite::Product',
-
:foreign_key=>'ProductID'
-
belongs_to :customer, :class_name=>'OldSite::Customer',
-
:foreign_key=>'CustomerID'
-
belongs_to :product_variant, :class_name=>'OldSite::ProductVariant',
-
:foreign_key=>'VariantID'
-
-
def certificates
-
order_number.certificates #.select{|c|c.product==product}
-
end
-
-
def order
-
order_number.order
-
end
-
-
def migrate(options)
-
new_order = options[:new_order]
-
new_order.description=[new_order.description,
-
self.OrderedProductDescription].join(': ')
-
unless options[:certs_created]
-
self.certificates.count.times do |i|
-
co=CertificateOrder.new(:created_at=>self.order.OrderDate)
-
co.sub_order_items << SubOrderItem.create(:product_variant_item=>
-
ProductVariantItem.find_by_serial('mssl'))
-
co.amount=(self.OrderedProductPrice*100).to_i/self.Quantity
-
co.preferred_payment_order='prepaid' if self.certificates[i].blank? ||
-
self.certificates[i].UnsignedCert.blank?
-
co.preferred_v2_product_description = product.Name
-
#co.pay! true
-
co.workflow_state='paid'
-
co.ssl_account=order.sa
-
items=orders_kit_carts.each_with_object([]) do |okc, arry|
-
arry << okc.KitItemName
-
end
-
co.v2_line_items=items unless items.empty?
-
co.line_item_qty=1
-
if co.save
-
ap "new ::CertificateOrder saved #{co.model_and_id}"
-
else
-
ap "failed save operation of ::CertificateOrder for #{new_order.model_and_id}"
-
end
-
li=new_order.line_items.create
-
li.cents=(self.OrderedProductPrice*100).to_i
-
li.sellable=co
-
if li.save
-
ap "new ::LineItem saved #{li.model_and_id}"
-
else
-
ap "failed save operation of ::LineItem for #{new_order.model_and_id}"
-
end
-
#saving processed certs for paid only orders
-
unless self.certificates[i].blank?
-
if co.valid?
-
self.certificates[i].migrate_cert_and_merchants(co)
-
else
-
msg="CertificateOrder is not valid for #{co}.
-
CertificateContents not created"
-
logger.error msg
-
ap msg
-
end
-
end
-
end
-
end
-
new_order
-
end
-
end
-
-
class Company < Base
-
set_table_name 'Company'
-
set_primary_key 'CompanyID'
-
has_many :customers, :class_name=>'OldSite::Customer',
-
:foreign_key=>'CompanyID'
-
end
-
-
class Merchant < Base
-
set_table_name 'Merchant'
-
set_primary_key 'MerchantID'
-
belongs_to :customer, :class_name=>'OldSite::Customer',
-
:foreign_key=>'CustomerID'
-
has_one :certificate, :class_name=>'OldSite::Certificate',
-
:foreign_key=>'MerchantID'
-
has_many :merchant_contacts, :class_name=>'OldSite::MerchantContact',
-
:foreign_key=>'MerchantID'
-
-
ATTR_MAP={
-
company_name: :MerchantName,
-
department: :MerchantDept,
-
address1: :MerchantStreet1,
-
address2: :MerchantStreet2,
-
city: :MerchantCity,
-
state: :MerchantState,
-
country: :MerchantCountry,
-
postal_code: :MerchantPostalCode
-
}
-
-
def migrate(cc)
-
self.copy_attributes_to(cc.create_registrant).tap do |r|
-
if r.save && cc.workflow_state!='issued'
-
cc.update_attribute :workflow_state, 'info_provided'
-
end
-
end
-
end
-
-
def copy_attributes_to(registrant)
-
registrant.tap do |r|
-
copy_attributes(r)
-
end
-
end
-
end
-
-
class MerchantContact < Base
-
set_table_name 'MerchantContacts'
-
set_primary_key 'MerchantContactID'
-
belongs_to :merchant, :class_name=>'OldSite::Merchant',
-
:foreign_key=>'MerchantID'
-
belongs_to :contact_type, :class_name=>'OldSite::ContactType',
-
:foreign_key=>'ContactType'
-
-
ATTR_MAP={title: :MCTitle,
-
first_name: :MCFirstName,
-
last_name: :MCLastName,
-
company_name: :MCCompanyName,
-
department: :MCDepartment,
-
address1: :MCStreet1,
-
address2: :MCStreet2,
-
city: :MCCity,
-
state: :MCState,
-
country: :MCCountry,
-
postal_code: :MCPostalCode,
-
email: :MCEmailAddress,
-
phone: :MCPhoneNumber,
-
ext: :MCExtension,
-
fax: :MCFaxNumber,
-
notes: :MCNotes}
-
-
def self.convert_country(old_country)
-
country=Country.find_by_iso3_code(old_country) ||
-
Country.find_by_iso1_code(old_country) ||
-
Country.find_by_name_caps(old_country.upcase)
-
country.blank? ? nil : country.iso1_code
-
end
-
-
def migrate(cc)
-
unless self.MerchantID==0
-
cc.certificate_contacts.build.tap do |c_contact|
-
self.copy_attributes_to c_contact
-
if c_contact.save
-
cc.update_attribute :workflow_state, 'contacts_provided' unless
-
cc.workflow_state=='issued'
-
end
-
end
-
end
-
end
-
-
def copy_attributes_to(certificate_contact)
-
certificate_contact.tap do |cc|
-
type=self.contact_type.ContactTypeDesc.downcase
-
cc.roles = type=='business' ? %w(validation) : [type]
-
copy_attributes(cc)
-
end
-
end
-
end
-
-
class ServerType < Base
-
set_table_name 'ServerType'
-
set_primary_key 'ServerTypeID'
-
@@st = OldSite::ServerType.all
-
-
#new-old array
-
MAPPING=[[*(1..5)], [*(1..5)]].transpose + [[8,6], [9,7]] +
-
[[*(12..19)], [*(8..15)]].transpose + [[*(21..24)],
-
[*(16..19)]].transpose + [[*(26..34)], [*(20..28)]].transpose +
-
[[36,29]]
-
-
def self.server_software(id)
-
server_software_by_id(id) || server_software_by_desc(id) ||
-
server_software_by_code(id) || server_software_by_code('OTH')
-
end
-
-
def self.server_software_by_id(id)
-
st=@@st.find{|ss|ss.ServerTypeID==id.to_i}
-
ServerSoftware.find(MAPPING.find{|m|m[1]==st.ServerTypeID}[0]) if st
-
end
-
-
def self.server_software_by_desc(desc)
-
st=@@st.find{|ss|ss.ServerTypeDesc==desc}
-
ServerSoftware.find(MAPPING.find{|m|m[1]==st.ServerTypeID}[0]) if st
-
end
-
-
def self.server_software_by_code(code)
-
st=@@st.find{|ss|ss.ServerTypeSymbol==code}
-
ServerSoftware.find(MAPPING.find{|m|m[1]==st.ServerTypeID}[0]) if st
-
end
-
-
end
-
-
class ContactType < Base
-
set_table_name 'ContactType'
-
set_primary_key 'ContactTypeID'
-
has_many :merchant_contacts, :class_name=>'OldSite::MerchantContact',
-
:foreign_key=>'ContactType'
-
end
-
-
class Product < Base
-
set_table_name 'Product'
-
set_primary_key 'ProductID'
-
belongs_to :manufacturer, :class_name=>'OldSite::Manufacturer',
-
:foreign_key=>'ManufacturerID'
-
has_one :certificate_product, :class_name=>
-
'OldSite::CertificateProduct', :foreign_key=>'ProductID'
-
has_many :kit_carts, :class_name=>'OldSite::KitCart',
-
:foreign_key=>'CustomerID'
-
has_many :product_variants, :class_name=>
-
'OldSite::ProductVariant', :foreign_key=>'ProductID'
-
has_many :kit_groups, :class_name=>'OldSite::KitGroup',
-
:foreign_key=>'ProductID'
-
end
-
-
class ProductVariant < Base
-
set_table_name 'ProductVariant'
-
set_primary_key 'VariantID'
-
belongs_to :product, :class_name=>'OldSite::Product',
-
:foreign_key=>'ProductID'
-
has_one :certificate_product, :class_name=>
-
'OldSite::CertificateProduct', :foreign_key=>'ProductID'
-
has_many :orders_kit_carts, :class_name=>'OldSite::OrdersKitCart',
-
:foreign_key=>'VariantID'
-
end
-
-
class CertificateProduct < Base
-
set_table_name 'CertificateProduct'
-
set_primary_key 'CPID'
-
belongs_to :product, :class_name=>'OldSite::Product',
-
:foreign_key=>'ProductID'
-
has_many :certificates, :class_name=>'OldSite::Certificate',
-
:foreign_key=>'CertificateProductID'
-
end
-
-
class Manufacturer < Base
-
set_table_name 'Manufacturer'
-
set_primary_key 'ManufacturerID'
-
has_many :products, :class_name=>'OldSite::Product',
-
:foreign_key=>'ManufacturerID'
-
end
-
-
class OrderNumber < Base
-
set_table_name 'OrderNumbers'
-
set_primary_key 'OrderNumber'
-
has_many :orders_shopping_carts, :class_name=>
-
'OldSite::OrdersShoppingCart', :foreign_key=>'OrderNumber'
-
has_one :order, :class_name=>
-
'OldSite::Order', :foreign_key=>'OrderNumber'
-
has_many :certificates, :through=>:order
-
has_many :orders_kit_carts, :class_name=>'OldSite::OrdersKitCart',
-
:foreign_key=>'OrderNumber'
-
has_many :kit_carts, :through=>:orders_kit_carts,
-
:class_name=>'OldSite::KitCart', :foreign_key=>'KitCartRecID'
-
-
end
-
-
#basically a lineitem
-
class OrdersKitCart < Base
-
set_table_name 'Orders_KitCart'
-
set_primary_key 'OrderNumber, KitCartRecID'
-
# belongs_to :shopping_cart, :class_name=>'OldSite::ShoppingCart',
-
# :foreign_key=>'ShoppingCartRecID'
-
belongs_to :orders_shopping_cart, :class_name=>
-
'OldSite::OrdersShoppingCart', :foreign_key=>'ShoppingCartRecID',
-
:primary_key=>'ShoppingCartRecID'
-
belongs_to :kit_cart, :class_name=>'OldSite::KitCart',
-
:foreign_key=>'KitCartRecID'
-
belongs_to :order_number, :class_name=>'OldSite::OrderNumber',
-
:foreign_key=>'OrderNumber'
-
belongs_to :product, :class_name=>'OldSite::Product',
-
:foreign_key=>'ProductID'
-
belongs_to :product_variant, :class_name=>'OldSite::ProductVariant',
-
:foreign_key=>'VariantID'
-
belongs_to :customer, :class_name=>'OldSite::Customer',
-
:foreign_key=>'CustomerID'
-
belongs_to :kit_item, :class_name=>'OldSite::KitItem',
-
:foreign_key=>'KitItemID'
-
belongs_to :kit_group, :class_name=>'OldSite::KitGroup',
-
:foreign_key=>'KitGroupID'
-
end
-
-
class KitItem < Base
-
set_table_name 'KitItem'
-
set_primary_key 'KitItemID'
-
belongs_to :kit_group, :class_name=>'OldSite::KitGroup',
-
:foreign_key=>'KitGroupID'
-
end
-
-
class KitGroup < Base
-
set_table_name 'KitGroup'
-
set_primary_key 'KitGroupID'
-
belongs_to :product, :class_name=>'OldSite::Product',
-
:foreign_key=>'ProductID'
-
belongs_to :kit_group_type, :class_name=>'OldSite::KitGroupType',
-
:foreign_key=>'KitGroupTypeID'
-
has_many :kit_items, :class_name=>'OldSite::KitItem',
-
:foreign_key=>'KitGroupID'
-
end
-
-
class KitGroupType < Base
-
set_table_name 'KitGroupType'
-
set_primary_key 'KitGroupTypeID'
-
has_many :kit_groups, :class_name=>'OldSite::KitGroup',
-
:foreign_key=>'KitGroupTypeID'
-
end
-
-
class ShoppingCart < Base
-
set_table_name 'ShoppingCart'
-
set_primary_key 'ShoppingCartRecID'
-
has_one :orders_shopping_cart, :class_name=>
-
'OldSite::OrdersShoppingCart', :foreign_key=>'ShoppingCartRecID'
-
has_many :kit_carts, :class_name=>'OldSite::KitCart',
-
:foreign_key=>'ShoppingCartRecID'
-
belongs_to :customer, :class_name=>'OldSite::Customer',
-
:foreign_key=>'CustomerID'
-
end
-
-
#basically a lineitem
-
class KitCart < Base
-
set_table_name 'KitCart'
-
set_primary_key 'KitCartRecID'
-
belongs_to :customer, :class_name=>'OldSite::Customer',
-
:foreign_key=>'CustomerID'
-
belongs_to :shopping_cart, :class_name=>'OldSite::ShoppingCart',
-
:foreign_key=>'ShoppingCartRecID'
-
has_many :orders_kit_carts, :class_name=>'OldSite::OrdersKitCart',
-
:foreign_key=>'KitCartRecID'
-
has_many :order_numbers, :through=>:orders_kit_carts
-
-
def to_param
-
KitCartRecID
-
end
-
end
-
end if Rails.env=='development' && MIGRATING_FROM_LEGACY
-
-
require 'monitor'
-
require 'bigdecimal'
-
-
class Order < ActiveRecord::Base
-
extend Memoist
-
include V2MigrationProgressAddon
-
include SmimeClientEnrollable
-
-
belongs_to :billable, :polymorphic => true, touch: true
-
belongs_to :address
-
belongs_to :billing_profile, -> { unscope(where: [:status]) }
-
belongs_to :billing_profile_unscoped, foreign_key: :billing_profile_id, class_name: "BillingProfileUnscoped"
-
belongs_to :deducted_from, class_name: "Order", foreign_key: "deducted_from_id"
-
belongs_to :visitor_token
-
belongs_to :invoice, class_name: "Invoice", foreign_key: :invoice_id
-
belongs_to :reseller_tier, foreign_key: :reseller_tier_id
-
has_many :line_items, dependent: :destroy, after_add: Proc.new { |p, d| p.amount += d.amount}
-
has_many :certificate_orders, through: :line_items, :source => :sellable,
-
:source_type => 'CertificateOrder', unscoped: true
-
has_many :payments
-
has_many :transactions, class_name: 'OrderTransaction', dependent: :destroy
-
has_many :refunds, dependent: :destroy
-
has_many :order_transactions
-
has_many :taggings, as: :taggable
-
has_many :tags, through: :taggings
-
has_and_belongs_to_many :discounts
-
-
money :amount, cents: :cents
-
money :wildcard_amount, cents: :wildcard_cents
-
money :non_wildcard_amount, cents: :non_wildcard_cents
-
-
before_create :total, :determine_description
-
after_create :generate_reference_number, :commit_discounts, :domains_adjustment_notice
-
-
#is_free? is used to as a way to allow orders that are not charged (ie cent==0)
-
attr_accessor :is_free, :receipt, :deposit_mode, :temp_discounts
-
-
after_initialize do
-
if new_record?
-
self.amount = 0 if self.amount.blank?
-
self.is_free ||= false
-
self.receipt ||= false
-
self.deposit_mode ||= false
-
end
-
self.cur_wildcard = nil if self.cur_wildcard.blank?
-
self.cur_non_wildcard = nil if self.cur_non_wildcard.blank?
-
self.max_wildcard = nil if self.max_wildcard.blank?
-
self.max_non_wildcard = nil if self.max_non_wildcard.blank?
-
self.reseller_tier_id = nil if self.reseller_tier_id.blank?
-
self.wildcard_cents = 0 if self.wildcard_cents.blank?
-
self.non_wildcard_cents = 0 if self.non_wildcard_cents.blank?
-
end
-
-
FAW = "Funded Account Withdrawal"
-
DOMAINS_ADJUSTMENT = "Domains Adjustment"
-
SSL_CERTIFICATE = "SSL.com Certificate Order"
-
MI_PAYMENT = "Monthly Invoice Payment"
-
DI_PAYMENT = "Daily Invoice Payment"
-
S_OR_C_ENROLLMENT = "S/MIME or Client Enrollment"
-
CERTIFICATE_ENROLLMENT = "Certificate Enrollment"
-
-
# If team's billing_method is set to 'monthly', grab all orders w/'approved' approval
-
# when running charges at the end of the month for orders from ucc reprocessing.
-
BILLING_STATUS = %w{approved pending declined}
-
#go live with this
-
# default_scope{ includes(:line_items).where({line_items:}
-
# [:sellable_type !~ ResellerTier.to_s]} & (:billable_id - [13, 5146])).order('created_at desc')
-
#need to delete some test accounts
-
default_scope ->{includes(:line_items).where{state << ['payment_declined','fully_refunded','charged_back', 'canceled']}.
-
order("orders.created_at desc").uniq}
-
-
scope :not_new, lambda {
-
joins{line_items.sellable(CertificateOrder).outer}.
-
where{line_items.sellable(CertificateOrder).workflow_state=='paid'}.
-
joins{line_items.sellable(Deposit).outer}
-
}
-
-
scope :not_test, lambda {
-
joins{line_items.sellable(CertificateOrder).outer}.
-
where{(line_items.sellable(CertificateOrder).is_test==nil) |
-
(line_items.sellable(CertificateOrder).is_test==false)}
-
}
-
-
scope :is_test, -> {
-
joins{line_items.sellable(CertificateOrder)}.
-
where{(line_items.sellable(CertificateOrder).is_test==true)}
-
}
-
-
scope :search, lambda {|term|
-
term = term.strip.split(/\s(?=(?:[^']|'[^']*')*$)/)
-
filters = { amount: nil, email: nil, login: nil, account_number: nil, product: nil, created_at: nil,
-
discount_amount: nil, company_name: nil, ssl_slug: nil, is_test: nil, reference_number: nil,
-
monthly_invoice: nil, order_tags: nil
-
}
-
filters.each{|fn, fv|
-
term.delete_if {|s|s =~ Regexp.new(fn.to_s+"\\:\\'?([^']*)\\'?"); filters[fn] ||= $1; $1}
-
}
-
term = term.empty? ? nil : term.join(" ")
-
return nil if [term,*(filters.values)].compact.empty?
-
ref = (term=~/\b(co-[^\s]+)/ ? $1 : nil)
-
result = joins{}
-
result = result.joins{line_items.sellable(CertificateOrder)} if ref
-
unless term.blank?
-
result = result.joins{discounts.outer}.joins{billing_profile_unscoped.outer}.where{
-
(billing_profile_unscoped.last_digits == "#{term}") |
-
(billing_profile_unscoped.first_name =~ "%#{term}%") |
-
(billing_profile_unscoped.last_name =~ "%#{term}%") |
-
(billing_profile_unscoped.address_1 =~ "%#{term}%") |
-
(billing_profile_unscoped.address_2 =~ "%#{term}%") |
-
(billing_profile_unscoped.city =~ "%#{term}%") |
-
(billing_profile_unscoped.state =~ "%#{term}%") |
-
(billing_profile_unscoped.phone =~ "%#{term}%") |
-
(billing_profile_unscoped.country =~ "%#{term}%") |
-
(billing_profile_unscoped.company =~ "%#{term}%") |
-
(billing_profile_unscoped.notes =~ "%#{term}%") |
-
(billing_profile_unscoped.postal_code =~ "%#{term}%") |
-
(discounts.ref =~ "%#{term}%") |
-
(discounts.label =~ "%#{term}%") |
-
(reference_number =~ "%#{term}%") |
-
(notes =~ "%#{term}%") |
-
(ref ? (line_items.sellable(CertificateOrder).ref=~ "%#{ref}%") :
-
(notes =~ "%#{term}%")) # searching notes twice is a hack, nil did not work
-
}
-
end
-
%w(is_test).each do |field|
-
query=filters[field.to_sym]
-
if query.try("true?")
-
result = result.send(field)
-
else
-
result = result.not_test
-
end
-
end
-
%w(reference_number).each do |field|
-
query=filters[field.to_sym]
-
result = result.where(field.to_sym => query.split(',')) if query
-
end
-
%w(login email).each do |field|
-
query=filters[field.to_sym]
-
result = result.joins{billable(SslAccount).users}.where{
-
(billable(SslAccount).users.send(field.to_sym) =~ "%#{query}%")} if query
-
end
-
%w(account_number company_name ssl_slug).each do |field|
-
query=filters[field.to_sym]
-
result = result.joins{billable(SslAccount).outer}.where{
-
(billable(SslAccount).send((field=="account_number" ? "acct_number" : field).to_sym) =~ "%#{query}%")} if query
-
end
-
%w(product).each do |field|
-
query=filters[field.to_sym]
-
case query
-
when /domain_adjustments/
-
result = result.where(description: Order::DOMAINS_ADJUSTMENT)
-
when /deposit/
-
result = result.joins{line_items.sellable(Deposit)}
-
.where.not(description: Order::FAW)
-
when /faw/
-
result = result.joins{line_items.sellable(Deposit)}
-
.where(description: Order::FAW)
-
when /certificate/
-
result = result.joins{line_items.sellable(CertificateOrder)}
-
when /reseller/
-
result = result.joins{line_items.sellable(ResellerTier)}
-
when /ucc/,/evucc/,/basicssl/,/wildcard/,/ev/,/premiumssl/,/ev-code-signing/,/code-signing/
-
result = result.joins{line_items.sellable(CertificateOrder).sub_order_items.product_variant_item.product_variant_group.
-
variantable(Certificate)}.where{certificates.product=="#{query}"}
-
end
-
end
-
%w(amount).each do |field|
-
if filters[field.to_sym]
-
query=filters[field.to_sym].split("-")
-
if query.count==1
-
query=filters[field.to_sym]
-
case query
-
when /\A>/,/\A</
-
result = result.where{(cents > ("#{query[1..-1]}".to_f*100).to_i)}
-
else
-
result = result.where{(cents == ("#{query}".to_f*100).to_i)}
-
end
-
else
-
result = result.where{cents >> ((query[0].to_f*100).to_i..(query[1].to_f*100).to_i)}
-
end
-
end
-
end
-
%w(order_tags).each do |field|
-
query = filters[field.to_sym]
-
result = result.joins(:tags).where(tags: {name: query.split(',')}) if query
-
end
-
%w(created_at).each do |field|
-
query=filters[field.to_sym]
-
if query
-
query=query.split("-")
-
start = Date.strptime query[0], "%m/%d/%Y"
-
finish = query[1] ? Date.strptime(query[1], "%m/%d/%Y") : start+1.day
-
result = result.where{created_at >> (start..finish)}
-
end
-
end
-
result = result.where.not(invoice_id: nil) unless filters[:monthly_invoice].nil?
-
result.uniq.order("orders.created_at desc")
-
} do
-
-
def amount
-
sum(:cents)*0.01
-
end
-
end
-
-
scope :not_free, lambda{
-
not_new.where :cents.gt=>0
-
}
-
-
scope :tracked_visitor, ->{where{visitor_token_id != nil}}
-
-
scope :range, lambda{|start, finish|
-
if start.is_a? String
-
s= start =~ /\// ? "%m/%d/%Y" : "%m-%d-%Y"
-
f= finish =~ /\// ? "%m/%d/%Y" : "%m-%d-%Y"
-
start = Date.strptime start, s
-
finish = Date.strptime finish, f
-
end
-
where{created_at >> (start..finish)}.uniq
-
-
} do
-
-
def amount
-
sum(:cents)*0.01
-
end
-
end
-
-
preference :migrated_from_v2, :default=>false
-
-
SmimeClientEnrollValidate = Struct.new(:user_id, :order_id) do
-
def perform
-
user = User.find user_id
-
order = Order.find order_id
-
if user && order
-
order.smime_client_enroll_recipients(user_id)
-
end
-
end
-
end
-
-
def smime_client_enrollment_validate(user_id)
-
Delayed::Job.enqueue SmimeClientEnrollValidate.new(user_id, id)
-
end
-
-
def self.range_amount(start, finish)
-
amount = BigDecimal(range(start, finish).amount.to_s)
-
rounded = (amount * 100).round / 100
-
'%.02f' % rounded
-
end
-
-
def discount_amount(items=nil)
-
cur_amount = items ? line_items.map(&:cents).sum : amount.cents
-
t=0
-
unless id
-
temp_discounts.each do |d|
-
d=Discount.find(d)
-
d.apply_as=="percentage" ? t+=(d.value.to_f*cur_amount) : t+=(d.value.to_i)
-
end unless temp_discounts.blank?
-
else
-
self.discounts.each do |d|
-
d.apply_as=="percentage" ? t+=(d.value.to_f*cur_amount) : t+=(d.value.to_i)
-
end unless self.discounts.empty?
-
end
-
Money.new(t)
-
end
-
-
def lead_up_to_sale
-
u = billable.primary_user
-
history = u.browsing_history("01/01/2000", created_at, "desc")
-
history = history.compact.sort{|x,y|x[1][0]<=>y[1][0]}.last if history.count > 1
-
history.shift
-
(["Order for amount #{amount} was made on #{created_at}"]<<history).flatten
-
end
-
-
def finalize_sale(options)
-
params = options[:params]
-
self.deducted_from = options[:deducted_from]
-
self.apply_discounts(params) #this needs to happen before the transaction but after the final incarnation of the order
-
self.update_attribute :visitor_token, options[:visitor_token] if options[:visitor_token]
-
self.mark_paid!
-
self.credit_affiliate(options[:cookies])
-
self.commit_discounts
-
end
-
-
def apply_discounts(params)
-
if (params[:discount_code])
-
self.temp_discounts = []
-
general_discount = Discount.viable.general.find_by_ref(params[:discount_code])
-
if general_discount
-
self.temp_discounts << general_discount.id
-
end
-
end
-
end
-
-
def credit_affiliate(cookies)
-
if !(self.is_test? || self.cents==0)
-
if cookies[ShoppingCart::AID] && Affiliate.exists?(cookies[ShoppingCart::AID])
-
self.ext_affiliate_name="idevaffiliate"
-
self.ext_affiliate_id="72198"
-
else
-
case Settings.affiliate_program
-
when "idevaffiliate"
-
self.ext_affiliate_name="idevaffiliate"
-
self.ext_affiliate_id="72198"
-
when "shareasale"
-
self.ext_affiliate_name="shareasale"
-
self.ext_affiliate_id="50573"
-
end
-
end
-
self.ext_affiliate_credited=false
-
self.save validate: false
-
end
-
end
-
-
def total
-
unless reprocess_ucc_order? ||
-
invoice_payment? ||
-
on_payable_invoice? ||
-
voided_on_payable_invoice? ||
-
domains_adjustment? ||
-
no_limit_order?
-
-
self.amount = line_items.inject(0.to_money) {|sum,l| sum + l.amount }
-
end
-
end
-
memoize :total
-
-
def final_amount
-
Money.new(amount.cents)-discount_amount
-
end
-
-
include Workflow
-
workflow_column :state
-
-
workflow do
-
state :invoiced do
-
event :payment_authorized, transitions_to: :authorized
-
event :invoice_paid!, transitions_to: :paid_by_invoice
-
event :full_refund, transitions_to: :fully_refunded do |complete=true|
-
if original_order?
-
line_items.each {|li|li.sellable.refund! if(
-
li.sellable.respond_to?("refund!".to_sym) && !li.sellable.refunded?)} if complete
-
end
-
end
-
event :partial_refund, transitions_to: :partially_refunded do |ref|
-
li = line_items.find {|li| li.sellable.try(:ref) == ref}
-
if li
-
decrement! :cents, li.cents
-
if original_order? && li.sellable.respond_to?("refund!".to_sym) && !li.sellable.refunded?
-
li.sellable.refund!
-
end
-
end
-
end
-
event :reject, transitions_to: :rejected do |complete=true|
-
line_items.each {|li| li.sellable_unscoped.reject!} if complete
-
end
-
event :cancel, transitions_to: :canceled do |complete=true|
-
cancel_order
-
end
-
event :charge_back, transitions_to: :charged_back do |complete=true|
-
line_items.each {|li| li.sellable_unscoped.charge_back!} if complete
-
end
-
end
-
-
state :pending do
-
event :payment_invoiced, transitions_to: :invoiced
-
event :give_away, transitions_to: :payment_not_required
-
event :payment_authorized, transitions_to: :authorized
-
event :transaction_declined, :transitions_to => :payment_declined
-
event :reject, :transitions_to => :rejected do |complete=true|
-
line_items.each {|li|li.sellable_unscoped.reject!} if complete
-
end
-
end
-
-
state :authorized do
-
event :payment_captured, transitions_to: :paid
-
event :transaction_declined, transitions_to: :authorized
-
event :reject, :transitions_to => :rejected do |complete=true|
-
line_items.each {|li|li.sellable_unscoped.reject!} if complete
-
end
-
end
-
-
state :paid do
-
event :full_refund, transitions_to: :fully_refunded do |complete=true|
-
line_items.each {|li|li.sellable_unscoped.refund! if(
-
li.sellable_unscoped.respond_to?("refund!".to_sym) && !li.sellable_unscoped.refunded?)} if complete
-
end
-
event :partial_refund, transitions_to: :partially_refunded do |ref|
-
li=line_items.find {|li|li.sellable_unscoped.try(:ref)==ref}
-
if li
-
decrement! :cents, li.cents
-
li.sellable_unscoped.refund! if (li.sellable_unscoped.respond_to?("refund!".to_sym) && !li.sellable_unscoped.refunded?)
-
end
-
end
-
event :reject, :transitions_to => :rejected do |complete=true|
-
line_items.each {|li|li.sellable_unscoped.reject!} if complete
-
end
-
event :cancel, transitions_to: :canceled do |complete=true|
-
cancel_order
-
end
-
event :charge_back, transitions_to: :charged_back do |complete=true|
-
line_items.each {|li|li.sellable_unscoped.charge_back!} if complete
-
end
-
end
-
-
state :fully_refunded do
-
event :unrefund, transitions_to: :paid do |complete=true|
-
line_items.each {|li|
-
CertificateOrder.unscoped.find_by_id(li.sellable_id).unrefund! if li.sellable_type=="CertificateOrder"} if complete
-
end
-
event :charge_back, transitions_to: :charged_back do |complete=true|
-
line_items.each {|li|li.sellable_unscoped.charge_back!} if complete
-
end
-
event :reject, :transitions_to => :rejected do |complete=true|
-
line_items.each {|li|
-
CertificateOrder.unscoped.find_by_id(li.sellable_id).reject! if li.sellable_type=="CertificateOrder"} if complete
-
end
-
end
-
-
state :partially_refunded do
-
event :partial_refund, transitions_to: :partially_refunded do |ref, amount=nil|
-
item =line_items.find {|li|li.sellable_unscoped.try(:ref)==ref} || certificate_orders.find {|co| co.try(:ref)==ref}
-
if item
-
decrement! :cents, (amount ? amount : item.cents)
-
to_refund = item.is_a?(LineItem) ? item.sellable : item
-
to_refund.refund! if (to_refund.respond_to?("refund!".to_sym) && !to_refund.refunded?)
-
end
-
end
-
event :full_refund, transitions_to: :fully_refunded do |complete=true|
-
line_items.each {|li|li.sellable_unscoped.refund! if(
-
li.sellable_unscoped.respond_to?("refund!".to_sym) && !li.sellable_unscoped.refunded?)} if complete
-
end
-
event :unrefund, transitions_to: :paid do |complete=true|
-
line_items.each {|li|
-
CertificateOrder.unscoped.find_by_id(li.sellable_id).unrefund! if li.sellable_type=="CertificateOrder"} if complete
-
end
-
event :charge_back, transitions_to: :charged_back do |complete=true|
-
line_items.each {|li|li.sellable_unscoped.charge_back!} if complete
-
end
-
event :reject, :transitions_to => :rejected do |complete=true|
-
line_items.each {|li|
-
CertificateOrder.unscoped.find_by_id(li.sellable_id).reject! if li.sellable_type=="CertificateOrder"} if complete
-
end
-
end
-
-
state :charged_back
-
-
state :rejected do
-
event :partial_refund, transitions_to: :partially_refunded do |ref, amount=nil|
-
item =line_items.find {|li|li.sellable_unscoped.try(:ref)==ref} || certificate_orders.find {|co| co.try(:ref)==ref}
-
if item
-
decrement! :cents, (amount ? amount : item.cents)
-
to_refund = item.is_a?(LineItem) ? item.sellable : item
-
to_refund.refund! if (to_refund.respond_to?("refund!".to_sym) && !to_refund.refunded?)
-
end
-
end
-
event :full_refund, transitions_to: :fully_refunded do |complete=true|
-
line_items.each {|li|li.sellable_unscoped.refund! if(
-
li.sellable_unscoped.respond_to?("refund!".to_sym) && !li.sellable_unscoped.refunded?)} if complete
-
end
-
event :unreject, transitions_to: :paid do |complete=true|
-
line_items.each {|li|
-
CertificateOrder.unscoped.find_by_id(li.sellable_id).unreject! if li.sellable_type=="CertificateOrder"} if complete
-
end
-
event :cancel, transitions_to: :canceled do |complete=true|
-
cancel_order
-
end
-
end
-
-
state :payment_declined do
-
event :give_away, transitions_to: :payment_not_required
-
event :payment_authorized, transitions_to: :authorized
-
event :transaction_declined, :transitions_to => :payment_declined
-
-
end
-
-
state :payment_not_required do
-
event :full_refund, transitions_to: :fully_refunded do |complete=true|
-
line_items.each {|li|li.sellable_unscoped.refund! if li.sellable_unscoped.respond_to?("refund!".to_sym)} if complete
-
end
-
event :cancel, transitions_to: :canceled do |complete=true|
-
cancel_order
-
end
-
event :reject, :transitions_to => :rejected do |complete=true|
-
line_items.each {|li|li.sellable_unscoped.reject!} if complete
-
end
-
end
-
-
state :canceled do
-
event :full_refund, transitions_to: :fully_refunded do |complete=true|
-
line_items.each {|li|li.sellable_unscoped.refund! if li.sellable_unscoped.respond_to?("refund!".to_sym)} if complete
-
end
-
event :cancel, transitions_to: :canceled do |complete=true|
-
cancel_order
-
end
-
event :charge_back, transitions_to: :charged_back do |complete=true|
-
line_items.each {|li|li.sellable_unscoped.charge_back!} if complete
-
end
-
event :reject, :transitions_to => :rejected do |complete=true|
-
line_items.each {|li|li.sellable_unscoped.reject!} if complete
-
end
-
end
-
end
-
-
## BEGIN acts_as_state_machine
-
#acts_as_state_machine :initial => :pending
-
#
-
#state :pending
-
#state :authorized
-
#state :paid
-
#state :fully_refunded
-
#state :payment_declined
-
#state :payment_not_required
-
#
-
#event :give_away do
-
# transitions :from => :pending,
-
# :to => :payment_not_required
-
#
-
# transitions :from => :payment_declined,
-
# :to => :payment_not_required
-
#end
-
#
-
#event :payment_authorized do
-
# transitions :from => :pending,
-
# :to => :authorized
-
#
-
# transitions :from => :payment_declined,
-
# :to => :authorized
-
#end
-
#
-
#event :payment_captured do
-
# transitions :from => :authorized,
-
# :to => :paid
-
#end
-
#
-
#event :transaction_declined do
-
# transitions :from => :pending,
-
# :to => :payment_declined
-
#
-
# transitions :from => :payment_declined,
-
# :to => :payment_declined
-
#
-
# transitions :from => :authorized,
-
# :to => :authorized
-
#end
-
#
-
#event :full_refund do
-
# transitions :from => :paid,
-
# :to => :fully_refunded
-
#end
-
## END acts_as_state_machine
-
-
# BEGIN number
-
-
def get_full_refund_amount
-
refunded = 0
-
if fully_refunded?
-
funded_amt = get_funded_account_amount
-
not_standard = on_payable_invoice? || (domains_adjustment? && funded_amt > 0)
-
refunded = (not_standard ? cents : get_total_merchant_amount) + funded_amt
-
end
-
-
if partially_refunded?
-
refunded_items = CertificateOrder.unscoped
-
.where(id: line_items.map(&:sellable_id), workflow_state: 'refunded')
-
if refunded_items.any?
-
refunded_items.each { |item| refunded += make_available_line(item) }
-
else
-
refunded = get_total_merchant_refunds
-
end
-
end
-
refunded
-
end
-
-
def merchant_fully_refunded?
-
get_total_merchant_refunds == get_total_merchant_amount
-
end
-
-
def no_limit_order?
-
state == 'invoiced'
-
end
-
-
def voided_on_payable_invoice?
-
!invoice_id.blank? && (
-
fully_refunded? ||
-
partially_refunded? ||
-
canceled? ||
-
rejected? ||
-
charged_back?
-
)
-
end
-
-
def on_payable_invoice?
-
!invoice_id.blank? && state == 'invoiced'
-
end
-
-
def approved_for_invoice?
-
on_payable_invoice? && approval == 'approved'
-
end
-
-
def removed_from_invoice?
-
on_payable_invoice? && approval == 'rejected'
-
end
-
-
def invoice_address
-
Invoice.find_by(order_id: id)
-
end
-
-
def reprocess_ucc_order?
-
self.type == 'ReprocessCertificateOrder'
-
end
-
-
def domains_adjustment?
-
description == DOMAINS_ADJUSTMENT
-
end
-
-
def reprocess_ucc_free?
-
reprocess_ucc_order? && cents==0
-
end
-
-
def monthly_invoice_order?
-
# Payment for total of monthly invoice
-
description == MI_PAYMENT
-
end
-
-
def daily_invoice_order?
-
# Payment for total of daily invoice
-
description == DI_PAYMENT
-
end
-
-
def invoice_payment?
-
monthly_invoice_order? || daily_invoice_order?
-
end
-
-
def faw_order?
-
description == FAW # Funded Account Withdrawal
-
end
-
-
def get_order_type_label
-
if reprocess_ucc_order?
-
'(Reprocess)'
-
elsif domains_adjustment? && !reprocess_ucc_order?
-
'(Domains Adjustment)'
-
else
-
''
-
end
-
end
-
-
# Get all orders for certificate orders or line items of main order.
-
def get_cached_orders
-
certificate_orders.map(&:orders).inject([]) do |all, o|
-
all << o if o != self
-
all.flatten
-
end
-
end
-
-
# Fetches all domain counts that were added during UCC domains adjustment
-
def get_reprocess_domains
-
Rails.cache.fetch("#{cache_key}/get_reprocess_domains") do
-
co = certificate_orders.first
-
cc = get_reprocess_cc(co)
-
cs = cc.signed_certificate if cc
-
cc_domains = (cc.nil? || (cc && cc.domains.blank?)) ? [] : cc.domains
-
cur_domains = (cc && cs) ? cs.subject_alternative_names : cc_domains
-
non_wildcard = cur_domains.map {|d| d if !d.include?('*')}.compact
-
wildcard = cur_domains.map {|d| d if d.include?('*')}.compact
-
-
tot_non_wildcard = if cur_non_wildcard.blank?
-
non_wildcard.count - co.get_reprocess_max_nonwildcard(cc).count
-
else
-
cur_non_wildcard
-
end
-
-
tot_wildcard = if cur_wildcard.blank?
-
wildcard.count - co.get_reprocess_max_wildcard(cc).count
-
else
-
cur_wildcard
-
end
-
-
tot_non_wildcard = tot_non_wildcard < 0 ? 0 : tot_non_wildcard
-
tot_wildcard = tot_wildcard < 0 ? 0 : tot_wildcard
-
new_domains_count = tot_non_wildcard + tot_wildcard
-
-
{
-
all: cur_domains,
-
new_domains_count: (new_domains_count < 0 ? 0 : new_domains_count),
-
cur_wildcard: wildcard.count,
-
wildcard: tot_wildcard,
-
non_wildcard: tot_non_wildcard
-
}
-
end
-
end
-
-
def get_ccref_from_notes
-
unless notes.blank?
-
notes.split(').').first.split.last.delete(')')
-
end
-
end
-
-
def get_reprocess_cc(co)
-
cc = nil
-
if co
-
str = get_ccref_from_notes
-
cc = if str.nil?
-
[]
-
else
-
co.certificate_contents.where("ref = ? OR id = ?", str, str)
-
end
-
cc = cc.any? ? cc.first : nil
-
end
-
cc
-
end
-
-
def get_reprocess_orders
-
result = {}
-
cached_certificate_orders.includes(:orders).each do |co|
-
current = []
-
co.orders.order(created_at: :asc).each do |o|
-
if o.reprocess_ucc_order?
-
current << {
-
date: o.created_at.strftime('%F'),
-
order_ref: o.reference_number,
-
domains: o.get_reprocess_domains,
-
amount: o.get_full_reprocess_format
-
}
-
end
-
end
-
result[co.ref] = current if current.any?
-
end
-
result
-
end
-
-
def number
-
SecureRandom.base64(32)
-
end
-
-
def invoice_denied_order(ssl_account)
-
cur_invoice_id = Invoice.get_or_create_for_team(ssl_account).try(:id)
-
if cur_invoice_id
-
update(
-
state: 'invoiced',
-
invoice_id: cur_invoice_id,
-
approval: 'approved'
-
)
-
transactions.destroy_all
-
end
-
end
-
-
# BEGIN purchase
-
def purchase(credit_card, options = {})
-
options[:order_id] = number
-
transaction do
-
current_amount = options[:amount] ? Money.new(options[:amount]) : final_amount
-
authorization = OrderTransaction.purchase(current_amount, credit_card, options)
-
if authorization && authorization.is_a?(OrderTransaction)
-
transactions.push(authorization)
-
-
if authorization.success?
-
payment_authorized!
-
else
-
if !invoice_payment? && %w{insufficient_funds do_not_honor transaction_not_allowed}.include?(authorization.params[:decline_code])
-
unless invoiced?
-
OrderNotifier.invoice_declined_order(
-
order: self,
-
user_email: options[:owner_email],
-
decline_code: authorization.params[:decline_code]
-
).deliver_now
-
payment_invoiced!
-
end
-
else
-
transaction_declined!
-
errors[:base] << authorization.message
-
end
-
end
-
end
-
authorization
-
end
-
end
-
# END purchase
-
-
# BEGIN authorization_reference
-
def authorization_reference
-
if authorization = transactions.find_by_action_and_success('authorization',
-
true, :order => 'id ASC')
-
authorization.reference
-
end
-
end
-
# END authorization_reference
-
-
def generate_reference_number
-
update_attribute :reference_number, SecureRandom.hex(2)+
-
'-'+Time.now.to_i.to_s(32)
-
end
-
-
def commit_discounts
-
temp_discounts.each do |td|
-
discounts<<Discount.viable.find(td)
-
end unless temp_discounts.blank?
-
temp_discounts=nil
-
end
-
-
def cached_certificate_orders
-
CertificateOrder.unscoped.where(id: (Rails.cache.fetch("#{cache_key}/cached_certificate_orders") do
-
certificate_orders.pluck(:id)
-
end)).order(created_at: :desc)
-
end
-
memoize :cached_certificate_orders
-
-
def is_free?
-
@is_free.try(:==, true) || (cents==0)
-
end
-
-
def mark_paid!
-
payment_authorized! unless authorized?
-
payment_captured!
-
end
-
-
# def self.cart_items(session, cookies)
-
# session[:cart_items] = []
-
# unless SERVER_SIDE_CART
-
# cart_items = cart_contents
-
# cart_items.each_with_index{|line_item, i|
-
# pr=line_item[ShoppingCart::PRODUCT_CODE]
-
# if !pr.blank? &&
-
# ((line_item.count > 1 && Certificate.find_by_product(pr)) ||
-
# ActiveRecord::Base.find_from_model_and_id(pr))
-
# session[:cart_items] << line_item
-
# else
-
# cart_items.delete line_item
-
# delete_cart_items
-
# save_cart_items(cart_items)
-
# end
-
# }
-
# end
-
# end
-
-
# creates a new order based on this order, but still needs to be assigned to a purchased object
-
# the following are valid options:
-
# :description, :profile, :cvv, :amount
-
def rebill(options)
-
options.reverse_merge!({description: Order::SSL_CERTIFICATE,
-
profile: self.billing_profile, cvv: true})
-
options[:profile].cycled_years.map do |exp_year|
-
profile=options[:profile]
-
params = {expiration_year: exp_year, cvv: options[:cvv]}
-
if (Rails.env=~/development/i && defined?(BillingProfile::TEST_AMOUNT))
-
params.merge!(card_number: "4222222222222")
-
self.amount= BillingProfile::TEST_AMOUNT
-
end
-
credit_card = profile.build_credit_card(params)
-
next unless ActiveMerchant::Billing::Base.mode == :test ?
-
true : credit_card.valid?
-
self.description = options[:description]
-
gateway_response = self.purchase(credit_card, profile.build_info(options[:description]))
-
result=(gateway_response.success?).tap do |success|
-
if success
-
self.mark_paid!
-
return gateway_response
-
#do we want to save the billing profile? if so do it here
-
else
-
self.transaction_declined!
-
end
-
end
-
gateway_response
-
end.last
-
end
-
-
def self.referers_for_paid(how_many)
-
not_free.first(how_many).map{|o|
-
[o.reference_number, o.created_at, o.referer_urls] unless o.referer_urls.blank?}.compact.flatten
-
end
-
-
def to_param
-
reference_number
-
end
-
-
def display_state
-
display=case self.state
-
when "fully_refunded"
-
"(REFUNDED)"
-
when "charged_back"
-
"(CHARGEBACK)"
-
when "rejected"
-
"(REJECTED)"
-
else
-
""
-
end
-
# (is_test? ? "(TEST) " : "") + display
-
end
-
-
def is_deposit?
-
Deposit == line_items.first.sellable.class if line_items.first
-
end
-
-
def is_reseller_tier?
-
ResellerTier == line_items.first.sellable.class if line_items.first
-
end
-
-
def migrated_from
-
v=V2MigrationProgress.find_by_migratable(self, :all)
-
v.map(&:source_obj) if v
-
end
-
-
#the next 2 functions are for migration purposes
-
#this function shows order that have order total amount that do not match their child
-
#line_item totals
-
def self.totals_mismatched
-
includes(:line_items).all.select{|o|o.cents!=o.line_items.sum(:cents)}
-
end
-
-
#this function shows order that have order total amount are less then child
-
#line_item totals and may result in in line_items that should not exist
-
def self.with_too_many_line_items
-
includes(:line_items).all.select{|o|o.cents<o.line_items.sum(:cents)}
-
end
-
-
def referer_urls
-
visitor_token.trackings.non_ssl_com_referer.map(&:referer).map(&:url) if visitor_token
-
end
-
-
# We'll raise this exception in the case of an unsettled credit.
-
class UnsettledCreditError < RuntimeError
-
UNSETTLED_CREDIT_RESPONSE_REASON_CODE = '54'
-
-
def self.match?( response )
-
response.params['response_reason_code'] == UNSETTLED_CREDIT_RESPONSE_REASON_CODE
-
end
-
end
-
-
# ============================================================================
-
# Make available to customer
-
# ============================================================================
-
def make_available_total
-
get_total_merchant_amount + get_funded_account_amount
-
end
-
-
def make_available_line(item, type=nil)
-
order_total = domains_adjustment? ? get_full_reprocess_amount : line_items.pluck(:cents).sum
-
discount_amt = discount_amount(:items)
-
total = if domains_adjustment?
-
get_full_reprocess_amount
-
else
-
item.is_a?(LineItem) ? item.cents : item.amount
-
end
-
percent = total.to_d/order_total.to_d
-
discount = (discount_amt.blank? || discount_amt.cents == 0) ? 0 : (discount_amt.cents * percent)
-
funded = get_funded_account_amount == 0 ? 0 : (get_funded_account_amount * percent)
-
-
if type == :merchant
-
total - (discount + funded)
-
else
-
total - discount
-
end
-
end
-
-
def make_available_funded(item)
-
order_total = line_items.pluck(:cents).sum
-
total = item.is_a?(LineItem) ? item.cents : item.amount
-
percent = total.to_d/order_total.to_d
-
get_funded_account_amount == 0 ? 0 : (get_funded_account_amount * percent)
-
end
-
-
# If order has been transfered from another team, then the originating team
-
# should be credited. Lookup SystemAudit log for specific keywords
-
# to determine originating order.
-
def get_team_to_credit
-
order_transferred = SystemAudit
-
.where(target_type: 'Order', target_id: id)
-
.where("notes LIKE ?", "%from team%")
-
.order(created_at: :desc).last
-
unless order_transferred.nil?
-
from_team = order_transferred.notes.split.find {|str| str.include?('#')}
-
end
-
from_team = SslAccount.find_by(acct_number: from_team.gsub('#', '')) unless from_team.nil?
-
from_team.nil? ? billable : from_team
-
end
-
-
# ============================================================================
-
# REFUND (utilizes 3 merchants, Stripe, PaypalExpress and Authorize.net)
-
# ============================================================================
-
def refund_merchant(amount, reason, user_id)
-
o = get_order_charged
-
ot = o.transactions.last if (o && o.transactions.last)
-
new_refund = nil
-
if o && payment_refundable?
-
params = {
-
merchant: get_merchant,
-
user_id: user_id,
-
order: o,
-
amount: amount,
-
reason: reason,
-
order_transaction: ot
-
}
-
new_refund = Refund.refund_merchant(params)
-
end
-
-
unless invoice_payment?
-
if merchant_fully_refunded?
-
full_refund! unless fully_refunded?
-
if certificate_orders.any?
-
cached_certificate_orders.each {|co| co.refund! unless co.refunded?}
-
end
-
else
-
partial_refund! unless partially_refunded?
-
end
-
end
-
-
SystemAudit.create(
-
owner: User.find_by_id(user_id),
-
target: o,
-
action: "Refund #{new_refund.id} created for order #{o.reference_number}. It is now #{o.current_state}",
-
notes: "Originating order is #{self.reference_number}."
-
)
-
new_refund
-
end
-
-
def get_merchant
-
o = get_order_charged
-
return 'na' if o.payment_not_refundable?
-
return 'paypal' if o.payment_paypal?
-
return 'stripe' if o.payment_stripe?
-
return 'authnet' if o.payment_authnet?
-
return 'no_payment' if o.payment_not_required?
-
return 'zero_amt' if o.payment_zero?
-
return 'funded' if o.payment_funded_account_partial? || o.payment_funded_account?
-
return 'other'
-
end
-
-
def get_order_charged
-
deducted_from_id ? Order.find_by_id(deducted_from_id) : self
-
end
-
-
def get_total_merchant_amount
-
merchant = get_merchant
-
o = get_order_charged
-
return (o.transactions.map(&:cents).sum) if o && %w{stripe authnet}.include?(merchant)
-
return o.cents if o && merchant == 'paypal'
-
if o
-
if %w{no_payment zero_amt funded}.include?(merchant)
-
0
-
else
-
o.cents
-
end
-
else
-
0
-
end
-
end
-
-
def get_full_reprocess_amount
-
cur_amount = cents != get_total_merchant_amount ? cents : get_total_merchant_amount
-
cur_amount + get_funded_account_amount
-
end
-
-
def get_full_reprocess_format
-
Money.new(get_full_reprocess_amount).format
-
end
-
-
def get_paid_reprocess_amount
-
get_total_merchant_amount
-
end
-
-
def get_funded_account_order
-
# order for funded account withdrawal
-
Order.where('description LIKE ?', "%Funded Account Withdrawal%")
-
.where('notes LIKE ?', "%#{reference_number}%").last
-
end
-
-
def get_funded_account_amount
-
# order was partially paid by funded account?
-
found = get_funded_account_order
-
found ? found.cents : 0
-
end
-
-
def get_surplus_amount
-
# covered order amount and suplus credited to funded account?
-
get_total_merchant_amount - (cents - get_funded_account_amount)
-
end
-
-
def get_total_merchant_refunds
-
refunds.where(status: 'success').map(&:amount).sum
-
end
-
-
def payment_refundable?
-
target = get_merchant
-
!target.blank? && %w{stripe paypal authnet}.include?(target)
-
end
-
-
def payment_not_required?
-
state == 'payment_not_required'
-
end
-
-
def payment_not_refundable?
-
po_number || quote_number
-
end
-
-
def payment_zero?
-
[billable_type, notes, po_number, quote_number].compact.empty? &&
-
cents == 0 && !payment_not_required?
-
end
-
-
def payment_funded_account_partial?
-
description.include?('Funded Account Withdrawal')
-
end
-
-
def payment_funded_account?
-
billing_profile_id.nil? &&
-
po_number.nil? &&
-
quote_number.nil? &&
-
( notes.blank? || funded_account_w_notes? ) &&
-
transactions.empty? &&
-
deducted_from_id.nil? &&
-
state == 'paid'
-
end
-
-
def funded_account_w_notes?
-
!notes.blank? && (
-
notes.include?('Reprocess UCC') ||
-
notes.include?('Initial CSR') ||
-
notes.include?('Renewal UCC') ||
-
notes.include?('monthly invoice') ||
-
notes.include?('daily invoice')
-
)
-
end
-
-
def payment_stripe?
-
!payment_not_refundable? && transactions.any? &&
-
!transactions.last.reference.blank? &&
-
transactions.last.reference.include?('ch_')
-
end
-
-
def payment_authnet?
-
!payment_not_refundable? && transactions.any? &&
-
!transactions.last.reference.blank? &&
-
transactions.last.reference.include?('#purchase')
-
end
-
-
def payment_paypal?
-
!payment_not_refundable? && !notes.blank? && notes.include?('paidviapaypal')
-
end
-
-
# this builds non-deep certificate_orders(s) from the cookie params
-
def self.certificates_order(options)
-
options[:certificates].compact.each do |c|
-
next if c[ShoppingCart::PRODUCT_CODE]=~/\Areseller_tier/
-
if certificate = Certificate.for_sale.find_by_product(c[ShoppingCart::PRODUCT_CODE])
-
if certificate.is_free?
-
qty=c[ShoppingCart::QUANTITY].to_i > options[:max_free] ? options[:max_free] : c[ShoppingCart::QUANTITY].to_i
-
else
-
qty=c[ShoppingCart::QUANTITY].to_i
-
end
-
certificate_order = CertificateOrder.new(
-
:server_licenses => c[ShoppingCart::LICENSES],
-
:duration => c[ShoppingCart::DURATION],
-
:quantity => qty)
-
certificate_order.add_renewal c[ShoppingCart::RENEWAL_ORDER]
-
certificate_order.certificate_contents.build :domains => c[ShoppingCart::DOMAINS]
-
unless options[:current_user].blank?
-
options[:current_user].ssl_account.clear_new_certificate_orders
-
certificate_order.ssl_account=current_user.ssl_account
-
next unless options[:current_user].ssl_account.can_buy?(certificate)
-
end
-
#adjusting duration to reflect number of days validity
-
certificate_order = setup_certificate_order(certificate: certificate, certificate_order: certificate_order)
-
options[:certificate_orders] << certificate_order if certificate_order.valid?
-
elsif product = Product.find_by_serial(c[ShoppingCart::PRODUCT_CODE])
-
product_order = ProductOrder.new(product: product, amount: product.amount)
-
unless options[:current_user].blank?
-
options[:current_user].ssl_account.clear_new_product_orders
-
product_order.ssl_account=current_user.ssl_account
-
end
-
options[:certificate_orders] << product_order
-
end
-
end
-
options[:certificate_orders]
-
end
-
-
# builds out certificate_order at a deep level by building SubOrderItems for each certificate_order
-
def self.setup_certificate_order(options)
-
certificate, certificate_order = options[:certificate], options[:certificate_order]
-
duration = certificate.duration_in_days(options[:duration] || certificate_order.duration)
-
certificate_order.certificate_content.duration = duration
-
if certificate.is_ucc? || certificate.is_wildcard?
-
psl = certificate.items_by_server_licenses.find { |item|
-
item.value==duration.to_s }
-
so = SubOrderItem.new(:product_variant_item=>psl,
-
:quantity =>certificate_order.server_licenses.to_i,
-
:amount =>psl.amount*certificate_order.server_licenses.to_i)
-
certificate_order.sub_order_items << so
-
if certificate.is_ucc?
-
pd = certificate.items_by_domains.find_all { |item|
-
item.value==duration.to_s }
-
additional_domains = (certificate_order.domains.try(:size) || 0) - Certificate::UCC_INITIAL_DOMAINS_BLOCK
-
so = SubOrderItem.new(:product_variant_item=>pd[0],
-
:quantity =>Certificate::UCC_INITIAL_DOMAINS_BLOCK,
-
:amount =>pd[0].amount*Certificate::UCC_INITIAL_DOMAINS_BLOCK)
-
certificate_order.sub_order_items << so
-
# calculate wildcards by subtracting their total from additional_domains
-
wildcards = 0
-
if certificate.allow_wildcard_ucc? and !certificate_order.domains.blank?
-
wildcards = certificate_order.domains.find_all{|d|d =~ /\A\*\./}.count
-
additional_domains -= wildcards
-
end
-
if additional_domains > 0
-
so = SubOrderItem.new(:product_variant_item=>pd[1],
-
:quantity =>additional_domains,
-
:amount =>pd[1].amount*additional_domains)
-
certificate_order.sub_order_items << so
-
end
-
if wildcards > 0
-
so = SubOrderItem.new(:product_variant_item=>pd[2],
-
:quantity =>wildcards,
-
:amount =>pd[2].amount*wildcards)
-
certificate_order.sub_order_items << so
-
end
-
-
certificate_order.wildcard_count = wildcards
-
certificate_order.nonwildcard_count = (certificate_order.domains.try(:size) || 0) - wildcards
-
end
-
end
-
unless certificate.is_ucc?
-
pvi = certificate.items_by_duration.find { |item| item.value==duration.to_s }
-
so = SubOrderItem.new(:product_variant_item=>pvi, :quantity=>1,
-
:amount =>pvi.amount)
-
certificate_order.sub_order_items << so
-
end
-
certificate_order.amount = certificate_order.
-
sub_order_items.map(&:amount).sum
-
certificate_order.certificate_contents[0].
-
certificate_order = certificate_order
-
certificate_order
-
end
-
-
def primary_user
-
billable.primary_user
-
end
-
-
def is_test?
-
certificate_orders.is_test.count > 0
-
end
-
-
# This is the required step to save certificate_orders to this order
-
# creates certificate_orders (and 'support' objects ie certificate_contents and sub_order_items)
-
# to be save to line_item.
-
def add_certificate_orders(certificate_orders)
-
self.amount=0 #will be adding the line_items below
-
certificate_orders.select{|co|co.is_a? CertificateOrder}.each do |cert|
-
cert.quantity.times do |i|
-
new_cert = CertificateOrder.new(cert.attributes)
-
cert.sub_order_items.each {|soi|
-
new_cert.sub_order_items << SubOrderItem.new(soi.attributes)
-
}
-
cert.certificate_contents.each {|cc|
-
cc_tmp = CertificateContent.new(cc.attributes)
-
cc_tmp.certificate_order = new_cert
-
new_cert.certificate_contents << cc_tmp
-
}
-
new_cert.line_item_qty = cert.quantity if(i==cert.quantity-1)
-
new_cert.preferred_payment_order = 'prepaid'
-
#the line blow was concocted because a simple assignment resulted in
-
#the certificate_order coming up nil on each certificate_content
-
#and failing the has_csr validation in the certificate_order
-
# new_cert.certificate_contents.clear
-
# cert.certificate_contents.each {|cc|
-
# cc_tmp = cc.dclone
-
# cc_tmp.certificate_order = new_cert
-
# new_cert.certificate_contents << cc_tmp} unless cert.certificate_contents.blank?
-
self.line_items.build :sellable=>new_cert
-
end
-
end
-
end
-
-
def invoice_bill_to_str
-
invoice = Invoice.find_by(order_id: id)
-
o = get_order_charged
-
bt = invoice.nil? ? o.billing_profile : invoice
-
if bt
-
addr = []
-
addr << bt.company unless bt.company.blank?
-
addr << "#{bt.first_name} #{bt.last_name}"
-
addr << bt.address_1
-
addr << bt.address_2 unless bt.address_2.blank?
-
addr << "#{bt.city}, #{bt.state}, #{bt.postal_code}"
-
addr << bt.country
-
addr
-
else
-
[]
-
end
-
end
-
-
def original_order?
-
self.class == Order
-
end
-
-
private
-
-
def domains_adjustment_notice
-
if domains_adjustment? and Settings.invoice_notify
-
Assignment.users_can_manage_invoice(billable).each do |u|
-
OrderNotifier.domains_adjustment_new(user: u, order: self).deliver_now
-
end
-
end
-
end
-
-
def gateway
-
OrderTransaction.gateway
-
end
-
-
def payment_failed(response)
-
raise Payment::AuthorizationError.new(response.message)
-
end
-
-
def options_for_payment(options = {})
-
{:order_id => self.id, :customer => self.billable_id}.merge(options)
-
end
-
-
def determine_description
-
self.description ||= SSL_CERTIFICATE
-
#causing issues with size of description for larger orders
-
# self.description ||= self.certificate_orders.
-
# map(&:description).join(" : ")
-
end
-
-
def cancel_order
-
current_invoice = invoice
-
line_items.each {|li| li.sellable_unscoped.cancel!}
-
update(canceled_at: Time.now, invoice_id: nil)
-
if current_invoice && current_invoice.orders.empty?
-
current_invoice.destroy
-
end
-
end
-
end
-
class OrderNotifier < ActionMailer::Base
-
helper :application
-
include ActionView::Helpers::TextHelper
-
include ActionView::Helpers::SanitizeHelper
-
helper CertificateOrdersHelper
-
extend ActionView::Helpers::SanitizeHelper::ClassMethods
-
-
def test
-
p caller[0] =~ /`([^']*)'/ and $1
-
end
-
alias_method :something, :test
-
-
def enrollment_request_for_team(team, request, team_admin)
-
@url = certificate_enrollment_requests_url(
-
team.to_slug, commit: true, id: request.try(:id)
-
)
-
-
mail subject: "New Certificate Enrollment Request",
-
from: Settings.from_email.orders,
-
to: team_admin.email
-
end
-
-
def invoice_declined_order(params)
-
@order = params[:order]
-
@decline_code = params[:decline_code]
-
@user_email = params[:user_email]
-
mail subject: "Order was invoiced due to decline error from Stripe merchant.",
-
from: Settings.from_email.orders,
-
to: Settings.support_email
-
end
-
-
def order_transferred(params)
-
@order_list = params[:orders_list]
-
@co_list = params[:co_list]
-
@user = params[:user].email
-
@from_team = params[:from_sa]
-
@to_team = params[:to_sa]
-
@from_owner = @from_team.get_account_owner.email
-
@to_owner = @to_team.get_account_owner.email
-
-
mail subject: "Order(s) have been transferred from team #{@from_team.get_team_name} to team #{@to_team.get_team_name}.",
-
from: Settings.from_email.orders,
-
to: [@from_owner, @to_owner].uniq
-
end
-
-
def domains_adjustment_new(params)
-
@user = params[:user]
-
@order = params[:order]
-
@team = @order.billable
-
-
mail subject: "A new domains adjustment order has been placed for team #{@team.get_team_name}.",
-
from: Settings.from_email.orders,
-
to: @user.email
-
end
-
-
def payable_invoice_new(params)
-
@user = params[:user]
-
@invoice = params[:invoice]
-
@team = @invoice.billable
-
@invoice_type = @invoice.get_type_format.downcase
-
-
mail subject: "You have a new invoice for team #{@team.get_team_name}.",
-
from: Settings.from_email.orders,
-
to: @user.email
-
end
-
-
def payable_invoice_paid(params)
-
@user = params[:user]
-
@paid_by = params[:paid_by]
-
@invoice = params[:invoice]
-
@team = @invoice.billable
-
@invoice_type = @invoice.get_type_format.downcase
-
-
mail subject: "Payment has been submitted for invoice ##{@invoice.reference_number} for team #{@team.get_team_name}.",
-
from: Settings.from_email.orders,
-
to: @user.email
-
end
-
-
def reseller_certificate_order_paid(ssl_account, certificate_order)
-
@ssl_account = ssl_account
-
@certificate_order = certificate_order.reload
-
mail subject: "#{'(TEST) ' if certificate_order.is_test?}SSL.com #{certificate_order.certificate.description["certificate_type"]} Certificate Confirmation For #{certificate_order.subject} (Order ##{certificate_order.ref})",
-
from: Settings.from_email.orders,
-
to: certificate_order.valid_recipients_list
-
-
end
-
-
def certificate_order_prepaid(ssl_account, order)
-
@ssl_account = ssl_account
-
@order = order
-
mail subject: "SSL.com Confirmation for Order ##{order.reference_number}",
-
from: Settings.from_email.orders,
-
to: to_valid_list(ssl_account.receipt_recipients)
-
end
-
-
def certificate_order_paid(contact, certificate_order, renewal=false)
-
@renewal = renewal
-
setup(contact, certificate_order)
-
mail subject: "#{'(TEST) ' if certificate_order.is_test?}SSL.com #{certificate_order.certificate.description["certificate_type"]} Certificate #{@renewal ? "Renewal Processed" : "Confirmation"} For #{certificate_order.subject} (Order ##{certificate_order.ref})",
-
from: Settings.from_email.orders,
-
to: contact
-
end
-
-
def dcv_sent(contact, certificate_order, last_sent, host=nil)
-
# host: only passed when called from delayed_job since dynamic default_url_options
-
# are not set when job runs.
-
setup(contact, certificate_order)
-
@host = host
-
@last_sent = last_sent
-
param = {certificate_order_id: @certificate_order.ref}
-
@validation_url = if @host
-
File.join(@host, new_certificate_order_validation_path(param))
-
else
-
new_certificate_order_validation_url(param)
-
end
-
mail subject: "#{'(TEST) ' if certificate_order.is_test?}SSL.com Validation Request Will Be Sent for #{certificate_order.subject} (Order ##{certificate_order.ref})",
-
from: Settings.from_email.orders,
-
to: contact
-
-
end
-
-
def dcv_email_send(certificate_order, email_address, identifier, domain_list, domain_id = nil, ssl_slug = '', dcv_type = 'cert')
-
@contact = email_address
-
@domains = domain_list
-
@identifier = identifier
-
subject="Domain Control Validation for: "
-
if dcv_type == 'team'
-
params = {ssl_slug: ssl_slug, id: domain_id}
-
@validation_url = dcv_validate_domain_url(params)
-
subject<<"#{domain_list.join(', ')}"
-
else
-
params = {ssl_slug: ssl_slug}
-
@validation_url = dcv_all_validate_domains_url(params)
-
subject<<"#{domain_list.join(', ')}"
-
end
-
mail subject: subject,
-
from: Settings.from_email.no_reply,
-
to: @contact
-
end
-
-
def processed_certificate_order(options) # contact, certificate_order, file_path=nil, signed_certificate=nil)
-
(attachments[options[:certificate_order].friendly_common_name+'.zip'] = File.read(options[:file_path])) unless options[:file_path].blank?
-
setup(options[:contact], options[:certificate_order])
-
@certificate_content = options[:certificate_content] || options[:certificate_order].certificate_content
-
@signed_certificate=options[:signed_certificate] || @certificate_content ?
-
@certificate_content.signed_certificate : options[:certificate_order].signed_certificate
-
mail(
-
to: options[:contact],
-
from: Settings.from_email.orders,
-
subject: "#{'(TEST) ' if options[:certificate_order].is_test?}SSL.com #{options[:certificate_order].certificate.description["certificate_type"]} Certificate (#{@signed_certificate.validation_type.upcase}) Attached For #{@signed_certificate.common_name}"
-
)
-
end
-
-
def potential_trademark(contact, certificate_order, domains)
-
@domains = domains
-
@certificate_order=certificate_order
-
mail subject: "Potential Trademark Issue for #{certificate_order.ref}",
-
from: Settings.from_email.no_reply,
-
to: contact
-
end
-
-
def validation_documents_uploaded(contact, certificate_order, files)
-
@files=files
-
setup(contact, certificate_order)
-
mail subject: "#{'(TEST) ' if certificate_order.is_test?}Validation Documents For #{certificate_order.subject} Has Been Uploaded",
-
from: Settings.from_email.no_reply,
-
to: contact
-
end
-
-
def validation_documents_uploaded_comodo(contact, certificate_order, files)
-
@files=files
-
setup(contact, certificate_order)
-
mail subject: "#{'(TEST) ' if certificate_order.is_test?}Validation Documents For #{certificate_order.external_order_number} Has Been Uploaded",
-
from: "support@ssl.com",
-
to: contact
-
end
-
-
def request_comodo_refund(contact, external_order_number, refund_reason, from="support@ssl.com")
-
@refund_reason = refund_reason
-
@external_order_number = external_order_number
-
mail subject: "Cancel and refund #{external_order_number}",
-
from: from,
-
to: contact
-
end
-
-
def problem_ca_sending(contact, certificate_order, ca, from="support@ssl.com", error=nil)
-
@ca=ca
-
@error=error
-
@certificate_order = certificate_order
-
mail subject: "Problem sending to #{@ca} for #{@certificate_order.ref}",
-
from: from,
-
to: contact
-
end
-
-
def validation_approve(contact, certificate_order)
-
setup(contact, certificate_order)
-
mail subject: "#{'(TEST) ' if certificate_order.is_test?}SSL.com Certificate For #{certificate_order.subject} Has Been Approved",
-
from: Settings.from_email.orders,
-
to: contact.email
-
end
-
-
def validation_unapprove(contact, certificate_order, validation)
-
setup(contact, certificate_order)
-
@validation=validation
-
mail subject: "#{'(TEST) ' if certificate_order.is_test?}SSL.com Certificate For #{certificate_order.subject} Has Not Been Approved",
-
from: Settings.from_email.orders,
-
to: contact.email
-
end
-
-
def site_seal_approve(contact, certificate_order)
-
setup(contact, certificate_order)
-
mail subject: "#{'(TEST) ' if certificate_order.is_test?}SSL.com Smart SeaL For #{certificate_order.subject} Is Now Ready",
-
from: Settings.from_email.orders,
-
to: (contact.is_a?(Contact) ? contact.email : contact)
-
end
-
-
def site_seal_unapprove(contact, certificate_order)
-
abuse = "#{'(TEST) ' if certificate_order.is_test?}" +
-
(certificate_order.site_seal.canceled? ? "Abuse Reported: " : "")
-
setup(contact, certificate_order)
-
mail subject: abuse+"SSL.com Smart SeaL For #{certificate_order.subject} Has Been Disabled",
-
from: Settings.from_email.orders,
-
to: (contact.is_a?(Contact) ? contact.email : contact)
-
end
-
-
def deposit_completed(ssl_account, deposit)
-
@ssl_account= ssl_account
-
@deposit = deposit
-
mail from: Settings.from_email.orders,
-
to: to_valid_list(ssl_account.receipt_recipients),
-
subject: "SSL.com Deposit Confirmation ##{deposit.reference_number}"
-
end
-
-
def activation_confirmation(user)
-
@root_url = root_url
-
mail subject: "Activation Complete",
-
from: Settings.from_email.activations,
-
to: user.email
-
end
-
-
def signup_invitation(email, user, message)
-
setup_sender_info
-
@recipients = "#{email}"
-
@subject = "#{user.login} would like you to join #{Settings.community_name}!"
-
@sent_on = Time.now
-
@body[:user] = user
-
@body[:url] = signup_by_id_url(user, user.invite_code)
-
@body[:message] = message
-
end
-
-
def reset_password(user)
-
setup_email(user)
-
@subject += "#{Settings.community_name} User information"
-
end
-
-
def forgot_username(user)
-
setup_email(user)
-
@subject += "#{Settings.community_name} User information"
-
end
-
-
def api_executed(rendered, api_domain)
-
@rendered = rendered
-
mail subject: "SSL.com api command executed (#{api_domain})",
-
from: "noreply@ssl.com",
-
to: Settings.send_api_calls
-
end
-
-
def certificate_order_token_send(co, token)
-
@activation_link = confirm_url(token)
-
@certificate_order = co
-
@company_name = @certificate_order.locked_registrant ? @certificate_order.locked_registrant.company_name : ''
-
-
mail subject: "Certificate Activation Link",
-
from: Settings.from_email.no_reply,
-
to: co.get_download_cert_email
-
end
-
-
def serial_number_entropy(revocation_notification)
-
@revocation_notification = revocation_notification
-
mail subject: "SSL.com Certificate Replacement Due to Serial Number Entropy",
-
from: Settings.from_email.no_reply,
-
to: revocation_notification.email
-
end
-
-
def request_token_send(co, user, requestor)
-
@certificate_order = co
-
@user = user
-
@requestor = requestor
-
-
mail subject: "Certificate Activation Link",
-
from: "no-reply@ssl.com",
-
to: user.email
-
end
-
-
def callback_send(co, token, email)
-
phone_number = co.locked_registrant.blank? ? '' : co.locked_registrant.phone || ''
-
country_code = co.locked_registrant.blank? ? '' : co.locked_registrant.country_code || '1'
-
@telephone = '+' + country_code + '-' + phone_number
-
@validation_link = email_verification_url(token)
-
-
mail subject: "SSL.com callback verification for certificate ref #{co.ref}",
-
from: Settings.from_email.no_reply,
-
to: email
-
end
-
-
def manual_callback_send(co, datetime)
-
@date_time = datetime
-
mail subject: "Manual Callback for certificate ref : \"#{co.ref}\"",
-
from: Settings.from_email.no_reply,
-
to: Settings.support_email
-
end
-
-
def request_phone_number_approve(co, to_email)
-
@co_edit_page_path = edit_certificate_order_url(id: co.ref, registrant: false, approve_phone: true)
-
@cert_order_ref = co.ref
-
-
mail subject: "Request for approving Phone Number",
-
from: co.get_download_cert_email,
-
to: to_email
-
end
-
-
def notify_phone_number_approve(co, from_email)
-
phone_number = co.locked_registrant.phone
-
country_code = co.locked_registrant.country_code
-
@phone_number = "(+" + country_code + ") " + phone_number
-
@cert_order_ref = co.ref
-
-
mail subject: "Approved Phone Number",
-
from: from_email,
-
to: co.get_download_cert_email
-
end
-
-
protected
-
def setup_email(user)
-
@recipients = "#{user.email}"
-
setup_sender_info
-
@subject = "[#{Settings.community_name}] "
-
@sent_on = Time.now
-
@body[:user] = user
-
end
-
-
def setup_sender_info
-
@from = "The #{Settings.community_name} Team <#{Settings.support_email}>"
-
headers "Reply-to" => "#{Settings.support_email}"
-
@content_type = "text/plain"
-
end
-
-
def setup(contact, certificate_order)
-
@contact=contact
-
@certificate_order=certificate_order
-
end
-
-
def to_valid_list(list)
-
if list.is_a? Array
-
list.delete(true)
-
return list.map(&:split).compact.flatten.uniq
-
end
-
return list.split.uniq if list.is_a? String
-
end
-
end
-
class OrderTransaction < ActiveRecord::Base
-
include Stripeable
-
-
belongs_to :order
-
has_many :renewal_attempts
-
has_many :refunds, dependent: :destroy
-
-
serialize :params
-
serialize :avs
-
serialize :cvv
-
cattr_accessor :gateway
-
-
money :amount, cents: :cents, currency: false
-
-
scope :paid_successfully, lambda{
-
where{(success == true) & (amount > 0)}
-
}
-
-
scope :not_free, lambda{
-
where{amount > 0}
-
}
-
-
class << self
-
def authorize(amount, credit_card, options = {})
-
process('authorization', amount) do |gw|
-
gw.authorize(amount, credit_card, options)
-
end
-
end
-
-
def capture(amount, authorization, options = {})
-
process('capture', amount) do |gw|
-
gw.capture(amount, authorization, options)
-
end
-
end
-
-
def purchase(amount, credit_card, options = {})
-
if amount.cents == 0
-
ActiveMerchant::Billing::Response.new(true, "This transaction has been approved")
-
else
-
if BillingProfile.gateway_stripe?
-
OrderTransaction.stripe_purchase(amount, credit_card, options)
-
else
-
process('purchase', amount){|gw| gw.purchase(amount, credit_card, options)}
-
end
-
end
-
end
-
-
def credit(amount, ref, last_four)
-
process('credit', amount) do |gw|
-
gw.credit(amount, ref, last_four)
-
end
-
end
-
-
private
-
-
def process(action, amount = nil)
-
result = OrderTransaction.new
-
result.amount = amount.to_s
-
result.action = action
-
-
begin
-
response = yield gateway
-
-
result.success = response.success?
-
result.reference = response.authorization
-
result.message = response.message
-
result.params = response.params
-
result.test = response.test?
-
result.avs = response.avs_result
-
result.cvv = response.cvv_result
-
rescue ActiveMerchant::ActiveMerchantError => e
-
result.success = false
-
result.reference = nil
-
result.message = e.message
-
result.params = {}
-
result.test = gateway.test?
-
end
-
-
result
-
end
-
-
def gateway
-
#ActiveMerchant::Billing::Base.default_gateway
-
unless BillingProfile.gateway_stripe?
-
s = ::Rails.application.secrets
-
ActiveMerchant::Billing::AuthorizeNetGateway.new(
-
login: s.authorize_net_key,
-
password: s.authorize_net_trans_id
-
)
-
end
-
end
-
end
-
end
-
class OrganizationValidation < Validation
-
has_many :certificate_contents
-
end
-
class OtherPartyRequest < ActiveRecord::Base
-
belongs_to :other_party_requestable, polymorphic: true
-
belongs_to :user
-
serialize :email_addresses
-
-
validates :other_party_requestable, :email_addresses, presence: true
-
validate :email_addresses_formats
-
-
before_validation on: :create do |o|
-
o.identifier='opvr-'+SecureRandom.hex(1)+Time.now.to_i.to_s(32)
-
end
-
-
def email_addresses=(emails)
-
write_attribute(:email_addresses, emails.split(/[,\s]/).reject{|e|e.blank?})
-
end
-
-
-
private
-
def email_addresses_formats
-
return false if email_addresses.blank?
-
email_addresses.each do |e|
-
unless e =~ EmailValidator::EMAIL_FORMAT
-
errors[:base]<<"Ooops, looks like one or more email addresses has an invalid format. Please be sure all email addresses are properly formed."
-
break false
-
end
-
end
-
end
-
end
-
class OtherPartyValidationRequest < OtherPartyRequest
-
DCV_SECTION = "dcv"
-
DOCUMENTS_SECTION = "documents"
-
BOTH_SECTIONS = "both"
-
-
preference :show_order_number, :default=>false
-
preference :sections, :string, :default=>BOTH_SECTIONS
-
-
validate :allowed_to_create, on: :create
-
-
after_create do |o|
-
OtherPartyRequestMailer.request_validation(o).deliver
-
end
-
-
def allowed(email)
-
email_addresses.include?(email)
-
end
-
-
def hide_dcv?
-
preferred_sections==DOCUMENTS_SECTION
-
end
-
-
def hide_documents?
-
preferred_sections==DCV_SECTION
-
end
-
-
def hide_both?
-
preferred_sections==BOTH_SECTIONS
-
end
-
-
private
-
-
def allowed_to_create
-
emails=[]
-
co = other_party_requestable
-
emails << co.ssl_account.cached_users.map(&:email)
-
emails << co.other_party_validation_requests.map(&:email_addresses)
-
unless emails.flatten.include?(user.email)
-
errors[:base]<<"ooops, it looks like you do not have permission to send a request for validation on this order."
-
end
-
end
-
-
end
-
class Payment < ActiveRecord::Base
-
class AuthorizationError < StandardError; end
-
belongs_to :order
-
belongs_to :address
-
-
money :amount
-
-
def capture
-
response = ActiveMerchant::Billing::Base.default_gateway.capture(self.amount, self.confirmation)
-
update_attributes :cleared_at => Time.now, :confirmation => response.authorization
-
end
-
-
def void!
-
response = ActiveMerchant::Billing::Base.default_gateway.void(self.confirmation)
-
raise response.message unless response.success?
-
update_attribute :voided_at, Time.now
-
end
-
-
end
-
class Permission < ActiveRecord::Base
-
# attr_accessible :title, :body
-
has_and_belongs_to_many :roles
-
-
end
-
1
class PhysicalToken < ActiveRecord::Base
-
1
MAKE_AND_MODELS={Gemalto: %w(5100\ eToken), Yubico: %w(Yubikey\ FIPS\ 140-2)}
-
1
CARRIERS=%w(FedEx UPS USPS DHL in-person Not\ Yet\ Shipped)
-
-
1
belongs_to :certificate_order
-
1
belongs_to :signed_certificate
-
-
1
after_save do
-
# if tracking_number and new?
-
# ship_token!
-
# end
-
-
if tracking_number
-
if new?
-
shipping_method == 'Not Yet Shipped' ? in_stay! : ship_token!
-
elsif not_yet_shipped? && shipping_method != 'Not Yet Shipped'
-
ship_token!
-
elsif in_transit? && shipping_method == 'Not Yet Shipped'
-
in_stay!
-
end
-
end
-
end
-
-
1
include Workflow
-
1
workflow do
-
1
state :new do
-
1
event :in_stay, :transitions_to => :not_yet_shipped
-
1
event :ship_token, :transitions_to => :in_transit
-
1
event :confirm_serial, :transitions_to => :in_possession
-
1
event :soft_delete, :transitions_to => :soft_deleted
-
end
-
-
1
state :not_yet_shipped do
-
1
event :ship_token, :transitions_to => :in_transit
-
1
event :confirm_serial, :transitions_to => :in_possession
-
1
event :soft_delete, :transitions_to => :soft_deleted
-
end
-
-
1
state :in_transit do
-
1
event :in_stay, :transitions_to => :not_yet_shipped
-
1
event :shipping_recipient_confirmation, :transitions_to => :received
-
1
event :confirm_serial, :transitions_to => :in_possession
-
1
event :soft_delete, :transitions_to => :soft_deleted
-
end
-
-
1
state :received
-
1
state :in_possession
-
1
state :soft_deleted
-
end
-
-
1
def make_and_model
-
[manufacturer,model_number].join(" ")
-
end
-
-
1
scope :active, ->{where{(workflow_state << ['soft_deleted'])}}
-
end
-
# This class represents a template of an item or service that can be sold. See ProductOrder for a purchased
-
# instance of Product
-
-
class Product < ActiveRecord::Base
-
has_many :product_variant_groups, :as => :variantable
-
has_many :product_variant_items, through: :product_variant_groups
-
has_many :product_orders
-
# if this product is to be added to certificate_order as a line_item
-
has_many :sub_order_items, :as => :sub_itemable, :dependent => :destroy
-
acts_as_publishable :live, :draft, :discontinue_sell
-
# belongs_to :reseller_tier
-
serialize :icons
-
serialize :description
-
serialize :display_order
-
serialize :title
-
has_and_belongs_to_many :parent_products, class_name: 'Product', association_foreign_key:
-
:sub_product_id, join_table: 'products_sub_products'
-
has_and_belongs_to_many :sub_products, class_name: 'Product', foreign_key:
-
:sub_product_id, join_table: 'products_sub_products'
-
has_and_belongs_to_many :certificates
-
-
def price=(amount)
-
self.amount = amount.gsub(/\./,"").to_i
-
end
-
-
def api_product_code
-
ApiCertificateRequest::PRODUCTS.find{|k,v|
-
serial =~ Regexp.new(v)
-
}[0].to_s
-
end
-
end
-
# This represents a purchased instance of Product
-
-
class ProductOrder < ActiveRecord::Base
-
acts_as_sellable :cents => :amount, :currency => false
-
belongs_to :ssl_account
-
belongs_to :product
-
has_many :users, through: :ssl_account
-
has_and_belongs_to_many :parent_product_orders, class_name: 'ProductOrder', association_foreign_key:
-
:sub_product_order_id, join_table: 'product_orders_sub_product_orders' # this order belongs to other(s)
-
has_and_belongs_to_many :sub_product_orders, class_name: 'ProductOrder', foreign_key:
-
:sub_product_order_id, join_table: 'product_orders_sub_product_orders' # this order has other order(s)
-
#will_paginate
-
cattr_reader :per_page
-
@@per_page = 10
-
-
#used to temporarily determine lineitem qty
-
attr_accessor :quantity
-
preference :payment_order, :string, :default=>"normal"
-
-
#if the customer has not used this certificate order with a period of time
-
#it becomes expired and invalid
-
alias_attribute :expired, :is_expired
-
-
scope :search, lambda {|term, options|
-
{:conditions => ["ref #{SQL_LIKE} ?", '%'+term+'%']}.merge(options)
-
}
-
-
scope :range, lambda{|start, finish|
-
if start.is_a?(String)
-
(s= start =~ /\// ? "%m/%d/%Y" : "%m-%d-%Y")
-
start = Date.strptime(start, s)
-
end
-
if finish.is_a?(String)
-
(f= finish =~ /\// ? "%m/%d/%Y" : "%m-%d-%Y")
-
finish = Date.strptime(finish, f)
-
end
-
where{created_at >> (start..finish)}
-
} do
-
-
def amount
-
self.nonfree.sum(:amount)*0.01
-
end
-
end
-
-
FULL = 'full'
-
EXPRESS = 'express'
-
PREPAID_FULL = 'prepaid_full'
-
PREPAID_EXPRESS = 'prepaid_express'
-
VERIFICATION_STEP = 'Perform Validation'
-
FULL_SIGNUP_PROCESS = {:label=>FULL, :pages=>%W(Submit\ CSR Payment
-
Registrant Contacts #{VERIFICATION_STEP} Complete)}
-
EXPRESS_SIGNUP_PROCESS = {:label=>EXPRESS,
-
:pages=>FULL_SIGNUP_PROCESS[:pages] - %w(Contacts)}
-
PREPAID_FULL_SIGNUP_PROCESS = {:label=>PREPAID_FULL,
-
:pages=>FULL_SIGNUP_PROCESS[:pages] - %w(Payment)}
-
PREPAID_EXPRESS_SIGNUP_PROCESS = {:label=>PREPAID_EXPRESS,
-
:pages=>EXPRESS_SIGNUP_PROCESS[:pages] - %w(Payment)}
-
-
CSR_SUBMITTED = :csr_submitted
-
INFO_PROVIDED = :info_provided
-
REPROCESS_REQUESTED = :reprocess_requested
-
CONTACTS_PROVIDED = :contacts_provided
-
-
CA_CERTIFICATES = {SSLcomSHA2: "SSLcomSHA2"}
-
-
STATUS = {CSR_SUBMITTED=>'info required',
-
INFO_PROVIDED=> 'contacts required',
-
REPROCESS_REQUESTED => 'csr required',
-
CONTACTS_PROVIDED => 'validation required'}
-
-
RENEWING = 'renewing'
-
REPROCESSING = 'reprocessing'
-
RECERTS = [RENEWING, REPROCESSING]
-
RENEWAL_DATE_CUTOFF = 45.days.ago
-
RENEWAL_DATE_RANGE = 45.days.from_now
-
-
# changed for the migration
-
# unless MIGRATING_FROM_LEGACY
-
# validates :certificate, presence: true
-
# else
-
# validates :certificate, presence: true, :unless=>Proc.new {|co|
-
# !co.orders.last.nil? && (co.orders.last.preferred_migrated_from_v2 == true)}
-
# end
-
-
before_create do |co|
-
co.is_expired=false
-
co.ref='co-'+SecureRandom.hex(1)+Time.now.to_i.to_s(32)
-
end
-
-
after_initialize do
-
if new_record?
-
self.quantity ||= 1
-
end
-
end
-
-
include Workflow
-
workflow do
-
state :new do
-
event :pay, :transitions_to => :paid do |payment|
-
halt unless payment
-
end
-
end
-
-
state :paid do
-
event :cancel, :transitions_to => :canceled
-
event :refund, :transitions_to => :refunded
-
event :charge_back, :transitions_to => :charged_back
-
event :start_over, transitions_to: :paid do |complete=false|
-
if self.certificate_contents.count >1
-
self.certificate_contents.last.delete
-
else
-
duration = self.certificate_content.duration
-
temp_cc=self.certificate_contents.create(duration: duration)
-
# Do not delete the last one
-
(self.certificate_contents-[temp_cc]).each do |cc|
-
cc.delete if ((cc.csr or cc.csr.signed_certificate.blank?) || complete)
-
end
-
end
-
end
-
end
-
-
state :canceled do
-
event :refund, :transitions_to => :refunded
-
event :charge_back, :transitions_to => :charged_back
-
end
-
-
state :refunded do #only refund a canceled order
-
event :unrefund, :transitions_to => :paid
-
event :charge_back, :transitions_to => :charged_back
-
end
-
-
state :charged_back
-
end
-
-
def duration_remaining(options={duration: :order})
-
remaining_days(options)/total_days(options)
-
end
-
-
def used_days(options={round: false})
-
if signed_certificates && !signed_certificates.empty?
-
sum = (Time.now - signed_certificates.sort{|a,b|a.created_at.to_i<=>b.created_at.to_i}.first.effective_date)
-
(options[:round] ? sum.round : sum)/1.day
-
else
-
0
-
end
-
end
-
-
def remaining_days(options={round: false, duration: :order})
-
tot, used = total_days(options), used_days(options)
-
if tot && used
-
days = total_days(options)-used_days(options)
-
(options[:round] ? days.round : days)
-
end
-
end
-
-
-
# :actual is based on the duration of the signed cert, :order is the duration based on the certificate order
-
def total_days(options={round: false, duration: :order})
-
if options[:duration]== :actual
-
if signed_certificates && !signed_certificates.empty?
-
sum = (signed_certificates.sort{|a,b|a.created_at.to_i<=>b.created_at.to_i}.last.expiration_date -
-
signed_certificates.sort{|a,b|a.created_at.to_i<=>b.created_at.to_i}.first.effective_date)
-
(options[:round] ? sum.round : sum)/1.day
-
else
-
0
-
end
-
else
-
certificate_duration(:days)
-
end
-
end
-
-
# unit can be :days or :years
-
def certificate_duration(unit=:as_is)
-
years=if migrated_from_v2? && !preferred_v2_line_items.blank?
-
preferred_v2_line_items.split('|').detect{|item|
-
item =~/years?/i || item =~/days?/i}.scan(/\d+.+?(?:ear|ay)s?/).last
-
else
-
unless certificate.is_ucc?
-
sub_order_items.map(&:product_variant_item).detect{|item|item.is_duration?}.try(:description)
-
else
-
d=sub_order_items.map(&:product_variant_item).detect{|item|item.is_domain?}.try(:description)
-
unless d.blank?
-
d=~/(\d years?)/i
-
$1
-
end
-
end
-
end
-
if unit==:years
-
years =~ /\A(\d+)/
-
$1
-
elsif unit==:days
-
case years.gsub(/[^\d]+/,"").to_i
-
when 1
-
365
-
when 2
-
730
-
when 3
-
1095
-
when 4
-
1461
-
when 5
-
1826
-
end
-
elsif unit==:comodo_api
-
case years.gsub(/[^\d]+/,"").to_i
-
when 1
-
365
-
when 2
-
730
-
when 90 #trial
-
90
-
when 30 #trial
-
30
-
else #no ssl can go beyond 39 months. 36 months to make adding 1 or 2 years later easier
-
1095
-
end
-
else
-
years
-
end
-
end
-
-
def renewal_certificate
-
if migrated_from_v2?
-
Certificate.map_to_legacy(preferred_v2_product_description, 'renew')
-
elsif certificate.is_free?
-
Certificate.for_sale.find_by_product "basicssl"
-
else
-
certificate
-
end
-
end
-
-
def mapped_certificate
-
if migrated_from_v2?
-
Certificate.map_to_legacy(preferred_v2_product_description)
-
else
-
certificate
-
end
-
end
-
-
def description
-
product.title
-
end
-
-
#find the desired Certificate, choose among it’s product_variant_groups, and finally choose among it’s product_variant_items
-
#
-
#change certificate_order.sub_order_item[0] to the appropriate ProductVariantItem item
-
#certificate_content.duration needs to change if not free cert
-
#
-
#take product_variant_item
-
def change_certificate(pvi)
-
amount = pvi.amount
-
update_attribute :amount, amount #also can update domains, server licenses, etc
-
sub_order_items[0].product_variant_item=pvi
-
sub_order_items[0].amount=amount
-
sub_order_items[0].save
-
certificate_content.duration = pvi.duration #for free certs, set to nil
-
-
#change order amount
-
line_items[0].update_attribute :cents, amount
-
Order.connection.update(
-
"UPDATE `orders` SET cents = #{line_items.map(&:cents).sum} WHERE id = #{order.id}") #override readonly
-
-
#Adjust funded account
-
ssl_account.funded_account.update_attribute :cents, amount
-
end
-
-
def migrated_from_v2?
-
order.try(:preferred_migrated_from_v2)
-
end
-
-
def signup_process(cert=certificate)
-
unless skip_payment?
-
if ssl_account && ssl_account.has_role?('reseller')
-
unless cert.is_ev?
-
EXPRESS_SIGNUP_PROCESS
-
else
-
FULL_SIGNUP_PROCESS
-
end
-
else
-
FULL_SIGNUP_PROCESS
-
end
-
else
-
prepaid_signup_process(cert)
-
end
-
end
-
-
def self.skip_verification?(certificate)
-
certificate.skip_verification?
-
end
-
-
def skip_verification?
-
self.certificate.skip_verification?
-
end
-
-
def order_status
-
if is_ev?
-
"waiting for documents"
-
end
-
end
-
-
def prepaid_signup_process(cert=certificate)
-
if ssl_account && ssl_account.has_role?('reseller')
-
unless cert.is_ev?
-
PREPAID_EXPRESS_SIGNUP_PROCESS
-
else
-
PREPAID_FULL_SIGNUP_PROCESS
-
end
-
elsif cert.is_browser_generated_capable?
-
PREPAID_EXPRESS_SIGNUP_PROCESS
-
else
-
PREPAID_FULL_SIGNUP_PROCESS
-
end
-
end
-
-
def is_express_signup?
-
!signup_process[:label].scan(EXPRESS).blank?
-
end
-
-
def is_express_validation?
-
validation.validation_rulings.detect(&:new?) &&
-
!signup_process[:label].scan(EXPRESS).blank?
-
end
-
-
def certificate_content
-
certificate_contents.last
-
end
-
-
def csr
-
certificate_content.csr
-
end
-
-
def most_recent_csr
-
csrs.compact.last || parent.try(:most_recent_csr)
-
end
-
-
def effective_date
-
certificate_content.try("csr").try("signed_certificate").try("effective_date")
-
end
-
-
def expiration_date
-
certificate_content.csr.signed_certificate.expiration_date
-
end
-
-
def is_expired_credit?
-
is_expired? && certificate_content.new? && created_at < 6.months.ago
-
end
-
-
def subject
-
return unless certificate_content.try(:csr)
-
csr = certificate_content.csr
-
csr.signed_certificate.try(:common_name) || csr.common_name
-
end
-
alias :common_name :subject
-
-
def display_subject
-
return unless certificate_content.try(:csr)
-
csr = certificate_content.csr
-
names=csr.signed_certificate.subject_alternative_names unless csr.signed_certificate.blank?
-
names=names.join(", ") unless names.blank?
-
names || csr.signed_certificate.try(:common_name) || csr.common_name
-
end
-
-
def domains
-
if certificate_content.domains.kind_of?(Array)
-
certificate_content.domains.flatten
-
else
-
certificate_content.domains
-
end
-
end
-
-
def wildcard_domains
-
domains.find_all{|d|d=~/\A\*\./} unless domains.blank?
-
end
-
-
def nonwildcard_domains
-
domains-nonwildcard_domains unless domains.blank?
-
end
-
-
# count of domains bought
-
# type can be 'wildcard', 'all'
-
def purchased_domains(type="nonwildcard")
-
soid = sub_order_items.find_all{|item|item.
-
product_variant_item.is_domain?}
-
case type
-
when 'all'
-
soid.sum(:quantity)
-
when 'wildcard'
-
soid.find_all{|item|item.product_variant_item.serial=~ /wcdm/}.sum(&:quantity)
-
when 'nonwildcard'
-
soid.sum(&:quantity)-soid.find_all{|item|item.product_variant_item.serial=~ /wcdm/}.sum(&:quantity)
-
end
-
end
-
-
def order(reload=nil)
-
orders(reload).last
-
end
-
-
def apply_for_certificate(options={})
-
ComodoApi.apply_for_certificate(self, options)
-
end
-
-
def retrieve_ca_cert(email_customer=false)
-
if external_order_number && ca_certificate_requests.first.success?
-
retrieve=ComodoApi.collect_ssl(self)
-
if retrieve.response_code==2
-
csr.signed_certificates.create(body: retrieve.certificate, email_customer: email_customer)
-
self.orphaned_certificate_contents remove: true
-
end
-
end
-
end
-
-
def to_param
-
ref
-
end
-
-
def last_dcv_sent
-
return if csr.blank?
-
dcvs=csr.domain_control_validations
-
(%w(http https).include?(dcvs.last.try(:dcv_method))) ? dcvs.last : dcvs.last_sent
-
end
-
-
-
def self.to_api_string(options={})
-
domain = options[:domain_override] || "https://sws-test.sslpki.com"
-
options[:action]="create_ssl" if options[:action].blank?
-
case options[:action]
-
when /create_ssl/
-
'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X POST -d "'+
-
{account_key: "#{options[:ssl_account].api_credential.account_key if options[:ssl_account].api_credential}",
-
secret_key: "#{options[:ssl_account].api_credential.secret_key if options[:ssl_account].api_credential}",
-
product: options[:certificate].api_product_code,
-
period: options[:period]}.to_json.gsub("\"","\\\"") +
-
"\" #{domain}/certificates"
-
when /create_code_signing/
-
'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X POST -d "'+
-
{account_key: "#{options[:ssl_account].api_credential.account_key if options[:ssl_account].api_credential}",
-
secret_key: "#{options[:ssl_account].api_credential.secret_key if options[:ssl_account].api_credential}",
-
product: options[:certificate].api_product_code,
-
period: options[:period]}.to_json.gsub("\"","\\\"") +
-
"\" #{domain}/certificates"
-
when /create_code_signing/
-
'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X POST -d "'+
-
{account_key: "#{options[:ssl_account].api_credential.account_key if options[:ssl_account].api_credential}",
-
secret_key: "#{options[:ssl_account].api_credential.secret_key if options[:ssl_account].api_credential}",
-
product: options[:certificate].api_product_code,
-
period: options[:period]}.to_json.gsub("\"","\\\"") +
-
"\" #{domain}/certificates"
-
end
-
end
-
-
def to_api_string(options={action: "update"})
-
domain = options[:domain_override] || "https://sws-test.sslpki.com"
-
api_contacts, api_domains, cc, registrant_params = base_api_params
-
case options[:action]
-
when /update_dcv/
-
# registrant_params.merge!(api_domains).merge!(api_contacts)
-
api_params={account_key: "#{ssl_account.api_credential.account_key if ssl_account.api_credential}",
-
secret_key: "#{ssl_account.api_credential.secret_key if ssl_account.api_credential}",
-
domains: api_domains}
-
options[:caller].blank? ?
-
'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X PUT -d "'+
-
api_params.to_json.gsub("\"","\\\"") + "\" #{domain}/certificate/#{self.ref}" : api_params
-
when /update/
-
api_params={account_key: "#{ssl_account.api_credential.account_key if ssl_account.api_credential}",
-
secret_key: "#{ssl_account.api_credential.secret_key if ssl_account.api_credential}",
-
server_software: cc.server_software_id.to_s,
-
domains: api_domains,
-
contacts: api_contacts,
-
csr: certificate_content.csr.body}.merge!(registrant_params)
-
# registrant_params.merge!(api_domains).merge!(api_contacts)
-
options[:caller].blank? ? 'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X PUT -d "'+
-
api_params.to_json.gsub("\"","\\\"") + "\" #{domain}/certificate/#{self.ref}" : api_params
-
when /create_w_csr/
-
api_params={account_key: "#{ssl_account.api_credential.account_key if ssl_account.api_credential}",
-
secret_key: "#{ssl_account.api_credential.secret_key if ssl_account.api_credential}",
-
product: certificate.api_product_code,
-
period: certificate_duration(:comodo_api).to_s,
-
server_software: cc.server_software_id.to_s,
-
domains: api_domains,
-
contacts: api_contacts,
-
csr: certificate_content.csr.body}.merge!(registrant_params)
-
options[:caller].blank? ? 'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X POST -d "'+
-
api_params.to_json.gsub("\"","\\\"") + "\" #{domain}/certificates" : api_params
-
when /create/
-
api_params={account_key: "#{ssl_account.api_credential.account_key if ssl_account.api_credential}",
-
secret_key: "#{ssl_account.api_credential.secret_key if ssl_account.api_credential}",
-
product: certificate.api_product_code,
-
period: certificate_duration(:comodo_api).to_s,
-
domains: api_domains}
-
options[:caller].blank? ? 'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X POST -d "'+
-
api_params.to_json.gsub("\"","\\\"") + "\" #{domain}/certificates" : api_params
-
when /show/
-
api_params={account_key: "#{ssl_account.api_credential.account_key if ssl_account.api_credential}",
-
secret_key: "#{ssl_account.api_credential.secret_key if ssl_account.api_credential}",
-
query_type: ("all_certificates" unless signed_certificate.blank?), show_subscriber_agreement: "Y",
-
response_type: ("individually" unless signed_certificate.blank?)}
-
options[:caller].blank? ? 'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X GET -d "'+
-
api_params.to_json.gsub("\"","\\\"") + "\" #{domain}/certificate/#{self.ref}" : api_params
-
when /index/
-
api_params={account_key: "#{ssl_account.api_credential.account_key if ssl_account.api_credential}",
-
secret_key: "#{ssl_account.api_credential.secret_key if ssl_account.api_credential}"}
-
options[:caller].blank? ? 'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X GET -d "'+
-
api_params.to_json.gsub("\"","\\\"") + "\" #{domain}/certificates" : api_params
-
when /dcv_emails/
-
api_params={account_key: "#{ssl_account.api_credential.account_key if ssl_account.api_credential}",
-
secret_key: "#{ssl_account.api_credential.secret_key if ssl_account.api_credential}"}.
-
merge!(certificate.is_ucc? ? {domains: certificate_content.domains} : {domain: csr.common_name})
-
options[:caller].blank? ? 'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X GET -d "'+
-
api_params.to_json.gsub("\"","\\\"") + "\" #{domain}/certificates/validations/email" : api_params
-
when /dcv_methods_wo_csr/
-
api_params={account_key: "#{ssl_account.api_credential.account_key if ssl_account.api_credential}",
-
secret_key: "#{ssl_account.api_credential.secret_key if ssl_account.api_credential}"}
-
options[:caller].blank? ? 'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X GET -d "'+
-
api_params.to_json.gsub("\"","\\\"") + "\" #{domain}/certificate/#{ref}/validations/methods" : api_params
-
when /dcv_methods_w_csr/
-
api_params={account_key: "#{ssl_account.api_credential.account_key if ssl_account.api_credential}",
-
secret_key: "#{ssl_account.api_credential.secret_key if ssl_account.api_credential}",
-
csr: certificate_content.csr.body}
-
options[:caller].blank? ? 'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X POST -d "'+
-
api_params.to_json.gsub("\"","\\\"") + "\" #{domain}/certificates/validations/csr_hash" : api_params
-
end
-
end
-
-
def domains_and_common_name
-
certificate_content.domains_and_common_name
-
end
-
-
def base_api_params
-
cc = certificate_content
-
r = cc.registrant
-
registrant_params = r.blank? ? {} :
-
{organization_name: r.company_name,
-
organization_unit_name: r.department,
-
post_office_box: r.po_box,
-
street_address_1: r.address1,
-
street_address_2: r.address2,
-
street_address_3: r.address3,
-
locality_name: r.city,
-
state_or_province_name: r.state,
-
postal_code: r.postal_code,
-
country_name: r.country}
-
api_domains = {}
-
if !cc.domains.blank?
-
(cc.domains.flatten+[common_name]).each { |d|
-
cn=cc.certificate_names.find_by_name(d)
-
if cn
-
api_domains.merge!(d.to_sym => {dcv:
-
cn.domain_control_validations.last_method.try(:method_for_api) ||
-
ApiCertificateCreate_v1_4::DEFAULT_DCV_METHOD })
-
end
-
}
-
elsif cc.csr
-
api_domains.merge!(cc.csr.common_name.to_sym => {dcv: "#{last_dcv_sent ? last_dcv_sent.method_for_api : 'http_csr_hash'}"})
-
end
-
api_contacts = {}
-
CertificateContent::CONTACT_ROLES.each do |role|
-
contact=cc.certificate_contacts.find do |certificate_contact|
-
if certificate_contact.roles.include?(role)
-
api_contact={}
-
(CertificateContent::RESELLER_FIELDS_TO_COPY+['country']).each do |field|
-
api_contact.merge! field.to_sym => "#{certificate_contact.send(field.to_sym)}"
-
end
-
api_contacts.merge! role.to_sym => api_contact
-
end
-
end
-
end
-
return api_contacts, api_domains, cc, registrant_params
-
end
-
-
def add_renewal(ren)
-
unless ren.blank?
-
self.renewal_id=CertificateOrder.find_by_ref(ren).id
-
end
-
end
-
-
def self.link_renewal(old, new)
-
CertificateOrder.find_by_ref(new).update_column :renewal_id, CertificateOrder.find_by_ref(old).id
-
end
-
-
=begin
-
Renews certificate orders and also handles the billing aspects
-
Use the order's credit card, then the most recent successfully card card
-
Renew for the same number of years as original order
-
If order is over a certain amount, notify customer first and let them know they do not need to
-
do anything
-
=end
-
# notify can be "none", "success", or "all"
-
def do_auto_renew(notify="success")
-
#does a credit already exists for this cert order
-
if (renewal.blank? || renewal_attempts_old?) && (auto_renew.blank? || auto_renew=="scheduled")
-
purchase_renewal(notify)
-
end
-
end
-
-
def renewal_attempts_old?
-
renewal_attempts.blank? ? true : renewal_attempts.last.created_at < RENEWAL_DATE_CUTOFF
-
end
-
-
def validation_methods
-
validation.validation_rules.map(&:applicable_validation_methods).
-
flatten.uniq
-
end
-
-
def validation_rules_satisfied?
-
certificate_content.validated?
-
end
-
-
def is_unused_credit?
-
certificate_content.try("new?") && workflow_state=='paid'
-
end
-
-
def is_prepaid?
-
preferred_payment_order=='prepaid'
-
end
-
-
def skip_payment?
-
!!(is_prepaid? || (certificate_content && certificate_content.preferred_reprocessing?))
-
end
-
-
def is_intranet?
-
certificate_content.csr.is_intranet? if certificate_content.try(:csr)
-
end
-
-
def server_software
-
certificate_content.server_software
-
end
-
alias :software :server_software
-
-
def is_open_ssl?
-
[3, 4, 35, 39].include? software.id
-
end
-
-
def is_apache?
-
[3, 4].include? software.id
-
end
-
-
def is_amazon_balancer?
-
[39].include? software.id
-
end
-
-
def is_iis?
-
[18, 19, 20].include? software.id
-
end
-
-
def is_nginx?
-
[37].include? software.id
-
end
-
-
def is_cpanel?
-
[35].include? software.id
-
end
-
-
def is_red_hat?
-
[29].include? software.id
-
end
-
-
def is_plesk?
-
[25].include? software.id
-
end
-
-
def is_heroku?
-
[38].include? software.id
-
end
-
-
def has_bundle?
-
!!(is_red_hat? || is_plesk? || is_heroku? || is_amazon_balancer?)
-
end
-
-
def bundle_name
-
if has_bundle?
-
if is_apache? or is_amazon_balancer?
-
'Apache bundle (SSLCACertificateFile)'
-
elsif is_red_hat? || is_plesk?
-
'ca bundle (Apache SSLCACertificateFile)'
-
elsif is_heroku?
-
'ca bundle for Heroku'
-
end
-
else
-
""
-
end
-
end
-
-
def status
-
if certificate_content.new?
-
"unused. waiting on certificate signing request (csr) from customer"
-
elsif certificate_content.expired?
-
'n/a'
-
else
-
case certificate_content.workflow_state
-
when "csr_submitted"
-
"waiting on registrant information from customer"
-
when "info_provided"
-
"waiting on contacts information from customer"
-
when "reprocess_requested"
-
"reissue requested. waiting on certificate signing request (csr)from customer"
-
when "contacts_provided"
-
"waiting on validation from customer"
-
when "pending_validation", "validated"
-
last_sent=csr.last_dcv
-
if last_sent.blank?
-
'validating, please wait' #assume intranet
-
elsif %w(http https cname http_csr_hash https_csr_hash cname_csr_hash).include?(last_sent.try(:dcv_method))
-
'validating, please wait'
-
else
-
"waiting validation email response from customer"
-
end
-
when "issued"
-
if certificate_content.expiring?
-
if renewal && renewal.paid?
-
"renewed. see #{renewal.ref} for renewal"
-
else
-
"expiring. renew soon"
-
end
-
else
-
"issued"
-
end
-
when "canceled"
-
end
-
end
-
end
-
-
# depending on the server software type we will bundle different root and intermediate certs
-
# override is a target server software other than the default one for this order
-
def bundled_cert_names(override={})
-
if self.ca == CA_CERTIFICATES[:SSLcomSHA2]
-
if (is_open_ssl? && override[:components].blank?) || override[:is_open_ssl]
-
#attach bundle
-
Certificate::BUNDLES[:comodo][:sha2_sslcom_2014][:labels].select do |k,v|
-
if signed_certificate.try("is_ev?".to_sym)
-
k=="sslcom_ev_ca_bundle#{'_amazon' if is_amazon_balancer? || override[:server]=="amazon"}.txt"
-
elsif signed_certificate.try("is_dv?".to_sym)
-
k=="sslcom_addtrust_ca_bundle#{'_amazon' if is_amazon_balancer? || override[:server]=="amazon"}.txt"
-
elsif signed_certificate.try("is_ov?".to_sym)
-
k=="sslcom_high_assurance_ca_bundle#{'_amazon' if is_amazon_balancer? || override[:server]=="amazon"}.txt"
-
elsif certificate.is_ev?
-
k=="sslcom_ev_ca_bundle#{'_amazon' if is_amazon_balancer? || override[:server]=="amazon"}.txt"
-
elsif certificate.is_essential_ssl?
-
k=="sslcom_addtrust_ca_bundle#{'_amazon' if is_amazon_balancer? || override[:server]=="amazon"}.txt"
-
else
-
k=="sslcom_high_assurance_ca_bundle#{'_amazon' if is_amazon_balancer? || override[:server]=="amazon"}.txt"
-
end
-
end.map{|k,v|k}
-
else
-
if signed_certificate.try("is_ev?".to_sym)
-
Certificate::BUNDLES[:comodo][:sha2_sslcom_2014][:contents]["sslcom_ev#{'_amazon' if is_amazon_balancer? || ["amazon","iis"].include?(override[:server])}.txt"]
-
elsif signed_certificate.try("is_dv?".to_sym)
-
Certificate::BUNDLES[:comodo][:sha2_sslcom_2014][:contents]["sslcom_dv#{'_amazon' if is_amazon_balancer? || ["amazon","iis"].include?(override[:server])}.txt"]
-
elsif signed_certificate.try("is_ov?".to_sym)
-
Certificate::BUNDLES[:comodo][:sha2_sslcom_2014][:contents]["sslcom_ov#{'_amazon' if is_amazon_balancer? || ["amazon","iis"].include?(override[:server])}.txt"]
-
elsif certificate.is_ev?
-
Certificate::BUNDLES[:comodo][:sha2_sslcom_2014][:contents]["sslcom_ev#{'_amazon' if is_amazon_balancer? || ["amazon","iis"].include?(override[:server])}.txt"]
-
elsif certificate.is_essential_ssl?
-
Certificate::BUNDLES[:comodo][:sha2_sslcom_2014][:contents]["sslcom_dv#{'_amazon' if is_amazon_balancer? || ["amazon","iis"].include?(override[:server])}.txt"]
-
else
-
Certificate::BUNDLES[:comodo][:sha2_sslcom_2014][:contents]["sslcom_ov#{'_amazon' if is_amazon_balancer? || ["amazon","iis"].include?(override[:server])}.txt"]
-
end
-
end
-
else
-
if is_open_ssl? && override[:components].blank?
-
#attach bundle
-
Certificate::COMODO_BUNDLES.select do |k,v|
-
if certificate.serial=~/256sslcom/
-
if signed_certificate.try("is_ev?".to_sym)
-
k=="sslcom_ev_ca_bundle#{'_amazon' if is_amazon_balancer?}.txt"
-
#elsif certificate.is_free?
-
# k=="sslcom_free_ca_bundle.txt"
-
elsif signed_certificate.try("is_dv?".to_sym)
-
k=="sslcom_addtrust_ca_bundle#{'_amazon' if is_amazon_balancer?}.txt"
-
elsif signed_certificate.try("is_ov?".to_sym)
-
k=="sslcom_high_assurance_ca_bundle#{'_amazon' if is_amazon_balancer?}.txt"
-
elsif certificate.is_ev?
-
k=="sslcom_ev_ca_bundle#{'_amazon' if is_amazon_balancer?}.txt"
-
#elsif certificate.is_free?
-
# k=="sslcom_free_ca_bundle.txt"
-
elsif certificate.is_essential_ssl?
-
k=="sslcom_addtrust_ca_bundle#{'_amazon' if is_amazon_balancer?}.txt"
-
else
-
k=="sslcom_high_assurance_ca_bundle#{'_amazon' if is_amazon_balancer?}.txt"
-
end
-
elsif certificate.comodo_product_id==342
-
k=="free_ssl_ca_bundle#{'_amazon' if is_amazon_balancer?}.txt"
-
elsif certificate.comodo_product_id==43
-
k=="trial_ssl_ca_bundle#{'_amazon' if is_amazon_balancer?}.txt"
-
else
-
k=="ssl_ca_bundle#{'_amazon' if is_amazon_balancer?}.txt"
-
end
-
end.map{|k,v|k}
-
else
-
Certificate::COMODO_BUNDLES.select do |k,v|
-
if certificate.serial=~/256sslcom/
-
if signed_certificate.try("is_ev?".to_sym)
-
%w(SSLcomPremiumEVCA.crt COMODOAddTrustServerCA.crt AddTrustExternalCARoot.crt).include? k
-
elsif signed_certificate.try("is_dv?".to_sym)
-
%w(SSLcomAddTrustSSLCA.crt AddTrustExternalCARoot.crt).include? k
-
elsif signed_certificate.try("is_ov?".to_sym)
-
%w(SSLcomHighAssuranceCA.crt AddTrustExternalCARoot.crt).include? k
-
elsif certificate.is_ev?
-
%w(SSLcomPremiumEVCA.crt COMODOAddTrustServerCA.crt AddTrustExternalCARoot.crt).include? k
-
elsif certificate.is_essential_ssl?
-
%w(SSLcomAddTrustSSLCA.crt AddTrustExternalCARoot.crt).include? k
-
else
-
%w(SSLcomHighAssuranceCA.crt AddTrustExternalCARoot.crt).include? k
-
end
-
elsif [342, 343].include? certificate.comodo_product_id
-
%w(UTNAddTrustSGCCA.crt EssentialSSLCA_2.crt ComodoUTNSGCCA.crt AddTrustExternalCARoot.crt).include? k
-
elsif certificate.comodo_product_id==337 #also maybe 410 (evucc) we'll get there when we place that order
-
%w(COMODOExtendedValidationSecureServerCA.crt COMODOAddTrustServerCA.crt AddTrustExternalCARoot.crt).include? k
-
elsif certificate.comodo_product_id==361
-
%w(EntrustSecureServerCA.crt USERTrustLegacySecureServerCA.crt).include? k
-
else
-
%w(SSLcomHighAssuranceCA.crt AddTrustExternalCARoot.crt).include? k
-
end
-
end.map{|k,v|k}
-
end
-
end
-
end
-
-
def bundled_cert_dir
-
if self.ca == CA_CERTIFICATES[:SSLcomSHA2]
-
Settings.intermediate_certs_path+Certificate::BUNDLES[:comodo][:sha2_sslcom_2014][:dir]+"/"
-
else
-
Settings.intermediate_certs_path
-
end
-
end
-
-
def validation_stage_checkout_in_progress?
-
certificate_content.contacts_provided?
-
end
-
-
CertificateContent::CONTACT_ROLES.each do |role|
-
define_method("#{role}_contact") do
-
certificate_content.send("#{role}_contact".intern)
-
end
-
end
-
-
%W(processed receipt confirmation).each do |et|
-
define_method("#{et}_recipients") do
-
[].tap do |addys|
-
addys << ssl_account.reseller.email if
-
ssl_account.is_registered_reseller? &&
-
ssl_account.send("preferred_#{et}_include_reseller?")
-
et_tmp = (et=="processed" ? "processed_certificate" : et)
-
addys << ssl_account.send("preferred_#{et_tmp}_recipients") unless
-
ssl_account.send("preferred_#{et_tmp}_recipients")=="0"
-
addys << administrative_contact.email if
-
administrative_contact &&
-
ssl_account.send("preferred_#{et}_include_cert_admin?")
-
ct = (et=="processed" ? "tech" : "bill")
-
addys << billing_contact.email if
-
billing_contact && !et=="processed" &&
-
ssl_account.send("preferred_#{et}_include_cert_#{ct}?")
-
addys << technical_contact.email if
-
technical_contact && et=="processed" &&
-
ssl_account.send("preferred_#{et}_include_cert_#{ct}?")
-
end.uniq
-
end
-
end
-
-
# def receipt_recipients
-
# returning addys = [] do
-
# addys << ssl_account.reseller.email if
-
# ssl_account.is_registered_reseller? &&
-
# ssl_account.preferred_receipt_include_reseller?
-
# addys << ssl_account.preferred_receipt_recipients unless
-
# ssl_account.preferred_receipt_recipients.empty?
-
# addys << administrative_contact.email if
-
# ssl_account.preferred_receipt_include_cert_admin?
-
# addys << billing_contact.email if
-
# ssl_account.preferred_receipt_include_cert_bill?
-
# addys.uniq!
-
# end
-
# end
-
-
def certificate_chain_names
-
parse_certificate_chain.transpose[0]
-
end
-
-
def certificate_chain_types
-
parse_certificate_chain.transpose[1]
-
end
-
-
def parse_certificate_chain
-
preferred_certificate_chain.split(",").
-
map(&:strip).map{|a|a.split(":")}
-
end
-
-
def friendly_common_name
-
certificate_content.csr.signed_certificate.nonidn_friendly_common_name
-
end
-
-
def request_csr_from
-
-
end
-
-
def v2_line_items
-
preferred_v2_line_items.split('|') unless preferred_v2_line_items.blank?
-
end
-
-
def v2_line_items=(line_items)
-
self.preferred_v2_line_items = line_items.join('|')
-
end
-
-
def options_for_ca(options={})
-
{}.tap do |params|
-
cc=(options[:certificate_content] || certificate_content)
-
cc.csr.tap do |csr|
-
update_attribute(:ca, CA_CERTIFICATES[:SSLcomSHA2]) if self.ca.blank?
-
if options[:new].blank? && (csr.sent_success || external_order_number)
-
#assume reprocess, will need to look at ucc more carefully
-
params.merge!(
-
'orderNumber' => external_order_number,
-
'csr' => csr.to_api,
-
'prioritiseCSRValues' => 'N',
-
'isCustomerValidated' => 'N',
-
'responseFormat' => 1,
-
'showCertificateID' => 'N',
-
'foreignOrderNumber' => ref,
-
'countryName'=>csr.country
-
)
-
set_comodo_subca(params,options)
-
last_sent = csr.domain_control_validations.last_method
-
build_comodo_dcv(last_sent, params, options)
-
else
-
params.merge!(
-
'test' => (is_test || !(Rails.env =~ /production/i)) ? "Y" : "N",
-
'product' => options[:product] || mapped_certificate.comodo_product_id.to_s,
-
'serverSoftware' => cc.comodo_server_software_id.to_s,
-
'csr' => csr.to_api,
-
'prioritiseCSRValues' => 'N',
-
'isCustomerValidated' => 'N',
-
'responseFormat' => 1,
-
'showCertificateID' => 'N',
-
'foreignOrderNumber' => ref
-
)
-
last_sent = csr.last_dcv
-
#43 is the old comodo 30 day trial
-
#look at certificate_duration for more guidance, i don't think the following is ucc safe
-
days = certificate_duration(:comodo_api)
-
# temporary for a certain customer wanting to move over a number of domains to ssl.com
-
if [Certificate::COMODO_PRODUCT_MAPPINGS["free"], 43].include?(
-
mapped_certificate.comodo_product_id) #trial cert does not specify duration
-
params.merge!('days' => (days).to_s)
-
else
-
params.merge!('days' => (days+csr.days_left).to_s)
-
end
-
#ssl.com Sub CA certs
-
set_comodo_subca(params,options)
-
build_comodo_dcv(last_sent, params, options)
-
fill_csr_fields(params, cc.registrant)
-
unless csr.csr_override.blank?
-
fill_csr_fields params, csr.csr_override
-
end
-
if false #TODO make country override option
-
override_params(params) #essentialssl
-
end
-
if certificate.is_wildcard?
-
params.merge!('servers' => server_licenses.to_s || '1')
-
end
-
end
-
if certificate.is_ev?
-
params.merge!('joiCountryName'=>(cc.csr.csr_override || cc.registrant).country)
-
params.merge!('joiLocalityName'=>(cc.csr.csr_override || cc.registrant).city)
-
params.merge!('joiStateOrProvinceName'=>(cc.csr.csr_override || cc.registrant).state)
-
end
-
if certificate.is_ucc?
-
params.merge!(
-
'primaryDomainName'=>csr.common_name.downcase,
-
'maxSubjectCNs'=>1
-
)
-
params.merge!('days' => '1095') if params['days'].to_i > 1095 #Comodo doesn't support more than 3 years
-
end
-
end
-
end
-
end
-
-
def override_params(options)
-
options["countryName"]="US"
-
options["prioritiseCSRValues"]="N"
-
# options["product"]=301 #essentialssl
-
# options.merge!('caCertificateID' => 401) #essentialssl
-
end
-
-
def build_comodo_dcv(last_sent, params, options={})
-
if certificate.is_ucc?
-
dcv_methods_for_comodo=[]
-
new_domains, csr = (options[:certificate_content] ?
-
[options[:certificate_content].domains, options[:certificate_content].csr] : [self.domains, self.csr])
-
domains_for_comodo = (new_domains.blank? ? [csr.common_name] : ([csr.common_name]+new_domains)).flatten.uniq
-
domains_for_comodo.each do |d|
-
if certificate_content.certificate_names.find_by_name(d)
-
last = certificate_content.certificate_names.find_by_name(d).last_dcv_for_comodo
-
dcv_methods_for_comodo << (last.blank? ? ApiCertificateCreate_v1_4::DEFAULT_DCV_METHOD_COMODO : last)
-
end
-
end
-
params.merge!('domainNames' => domains_for_comodo.join(","))
-
params.merge!('dcvEmailAddresses' => dcv_methods_for_comodo.join(",")) if (dcv_methods_for_comodo && dcv_methods_for_comodo.count==domains_for_comodo.count)
-
else
-
if last_sent.blank? || last_sent.dcv_method=="http"
-
params.merge!('dcvMethod' => "HTTP_CSR_HASH")
-
elsif last_sent.dcv_method=="https"
-
params.merge!('dcvMethod' => "HTTPS_CSR_HASH")
-
elsif last_sent.try("is_eligible_to_send?")
-
params.merge!('dcvEmailAddress' => last_sent.email_address)
-
last_sent.send_dcv! unless last_sent.sent_dcv?
-
end
-
end
-
end
-
-
# Creates a new external ca order history by deleting the old external order id and requests thus allowing us
-
# to start a new history with comodo for an existing ssl.com cert order
-
# useful in the event Comodo take forever to make changes to an existing order (and sometimes cannot) so we
-
# just create a new one and have the old one refunded
-
def reset_ext_ca_order
-
csrs.compact.map(&:sent_success).flatten.compact.uniq.each{|a|a.delete}
-
cc=certificate_content
-
cc.preferred_reprocessing = false
-
cc.save validation: false
-
end
-
-
def change_ext_ca_order(new_number)
-
ss=csrs.compact.map(&:sent_success).flatten.compact.last
-
ss.update_column :response, ss.response.gsub(external_order_number, new_number.to_s)
-
update_column :external_order_number, new_number
-
end
-
-
# Resets this order as if it never processed
-
# <tt>complete</tt> - removes the certificate_content (and it's csr and other properties)
-
# <tt>ext_ca_orders</tt> - removes the external calls history to comodo for this order
-
def reset(complete=false,ext_ca_orders=false)
-
self.reset_ext_ca_order if ext_ca_orders
-
self.certificate_content.csr.delete unless certificate_content.csr.blank?
-
-
self.start_over!(complete) unless ['canceled', 'revoked'].
-
include?(self.certificate_content.workflow_state)
-
end
-
-
# Removes any certificate_contents that were not processed, except the last one
-
def orphaned_certificate_contents(options={})
-
cc_count = self.certificate_contents.count
-
return nil if cc_count <= 1
-
ccs = []
-
certificate_contents.each_with_index do |cc, i|
-
next if i == cc_count-1 # ignore the most recent certificate_content
-
if (cc.csr.blank? || cc.csr.signed_certificate.blank?)
-
if options[:remove]
-
cc.destroy
-
else
-
ccs << cc
-
end
-
end
-
end
-
ccs unless options[:remove]
-
end
-
-
def self.remove_all_orphaned
-
self.find_each{|co|co.orphaned_certificate_contents remove: true}
-
end
-
-
# Removes the last certificate_content in the event it was a mistake
-
def remove_last_certificate_content
-
self.certificate_content.destroy if self.certificate_contents.count > 1
-
end
-
-
def external_order_number_meta(options={})
-
if notes =~ /(DV|EV|OV)\#\d+/
-
if options[:external_order_number] && notes =~ /(DV|EV|OV)\##{options[:external_order_number]}/
-
return $1
-
elsif options[:validation_type] && notes =~ /#{options[:validation_type]}\#(\d+)/
-
return $1
-
else
-
return external_order_number_meta(external_order_number: external_order_number)
-
end
-
end
-
end
-
-
def sent_success_count
-
sent_success_map = csrs.map(&:sent_success)
-
sent_success_map.flatten.compact.uniq.count if
-
csrs && !sent_success_map.blank?
-
end
-
-
# Get the most recent certificate_id (useful for UCC replacements)
-
def external_certificate_id
-
all_csrs = certificate_contents.map(&:csr)
-
sent_success_map = all_csrs.map(&:sent_success)
-
sent_success_map.flatten.compact.uniq.first.certificate_id if
-
all_csrs && !sent_success_map.blank? &&
-
sent_success_map.flatten.compact.uniq.first
-
#all_csrs.sent_success.order_number if all_csrs && all_csrs.sent_success
-
end
-
-
def transfer_certificate_content(certificate_content)
-
self.site_seal.conditionally_activate! unless self.site_seal.conditionally_activated?
-
cc = self.certificate_content
-
if certificate_content.preferred_reprocessing?
-
self.certificate_contents << certificate_content
-
certificate_content.create_registrant(cc.registrant.attributes.except(*CertificateOrder::ID_AND_TIMESTAMP)).save
-
cc.certificate_contacts.each do |contact|
-
certificate_content.certificate_contacts << CertificateContact.new(contact.attributes.
-
except(*CertificateOrder::ID_AND_TIMESTAMP))
-
end
-
cc = self.certificate_content
-
else
-
cc.signing_request = certificate_content.signing_request
-
cc.server_software = certificate_content.server_software
-
end
-
if cc.new?
-
cc.submit_csr!
-
elsif cc.validated? || cc.pending_validation?
-
cc.pend_validation! if cc.validated?
-
end
-
cc
-
end
-
-
def all_domains
-
certificate_content.all_domains
-
end
-
-
private
-
-
def fill_csr_fields(options, obj)
-
f= {'organizationName' => obj.company_name,
-
'organizationalUnitName' => obj.department,
-
'postOfficeBox' => obj.po_box,
-
'streetAddress1' => obj.address1,
-
'streetAddress2' => obj.address2,
-
'streetAddress3' => obj.address3,
-
'localityName' => obj.city,
-
'stateOrProvinceName' => obj.state,
-
'postalCode' => obj.postal_code,
-
'countryName' => obj.country}
-
options.merge!(f.each{|k,v|f[k]=CGI.escape(v) unless v.blank?})
-
end
-
-
def post_process_csr
-
certificate_content.submit_csr!
-
if ssl_account.is_registered_reseller?
-
OrderNotifier.reseller_certificate_order_paid(ssl_account, self).deliver
-
else
-
receipt_recipients.each do |c|
-
OrderNotifier.certificate_order_paid(c, self).deliver
-
end
-
end
-
site_seal.conditionally_activate!
-
end
-
-
# will cycle through billing profile to purchase certificate order
-
# use the billing profile associated with this order
-
# otherwise, find most recent successfully purchased order and use it's billing profile,
-
# cannot rely on order transactions, since the data was not migrated
-
-
# notify can be "none", "success", or "all"
-
def purchase_renewal(notify)
-
bp=order.billing_profile
-
response=[bp, (ssl_account.cached_orders.map(&:billing_profile)-[bp]).shift].compact.each do |bp|
-
p "purchase using billing_profile_id==#{bp.id}"
-
options={profile: bp, cvv: false}
-
new_cert = self.dup
-
new_cert.certificate_contents.build
-
new_cert.duration=1 #only renew 1 year at a time
-
co = Order.setup_certificate_order(certificate: renewal_certificate, certificate_order: new_cert)
-
co.parent = self
-
reorder=ssl_account.purchase co
-
reorder.cents = co.attributes_before_type_cast["amount"].to_f
-
gateway_response=reorder.rebill(options)
-
RenewalAttempt.create(
-
certificate_order_id: self.id, order_transaction_id: gateway_response.id)
-
if gateway_response.success?
-
#self.quantity=1
-
#clone_for_renew([self], reorder)
-
#reorder.line_items.last.sellable.update_attribute :renewal_id, self.id
-
co.save
-
reorder.save
-
if notify=="success"
-
begin
-
logger.info "Sending notification to #{receipt_recipients.join(",")}"
-
body = OrderNotifier.certificate_order_paid(receipt_recipients, co, true)
-
body.deliver unless body.to.empty?
-
RenewalNotification.create(certificate_order_id:
-
co.id, subject: body.subject,
-
body: body, recipients: receipt_recipients)
-
rescue Exception=>e
-
logger.error e.backtrace.inspect
-
raise e
-
end
-
end
-
return gateway_response
-
else
-
co.destroy
-
end
-
gateway_response
-
end.last
-
end
-
-
#def purchase_using(profile)
-
# credit_card = ActiveMerchant::Billing::CreditCard.new({
-
# :first_name => profile.first_name,
-
# :last_name => profile.last_name,
-
# :number => profile.card_number,
-
# :month => profile.expiration_month,
-
# :year => profile.expiration_year
-
# })
-
# credit_card.type = 'bogus' if defined?(::GATEWAY_TEST_CODE)
-
#end
-
-
def clone_for_renew(certificate_orders, order)
-
certificate_orders.each do |cert|
-
cert.quantity.times do |i|
-
#could use cert.dup after >=3.1, but we are currently on 3.0.10 so we'll do this manually
-
new_cert = cert.dup
-
cert.sub_order_items.each {|soi|
-
new_cert.sub_order_items << soi.dup
-
}
-
if cert.migrated_from_v2?
-
pvg = new_cert.sub_order_items[0].
-
product_variant_item.product_variant_group
-
pvg.variantable=cert.renewal_certificate
-
pvg.save
-
end
-
new_cert.line_item_qty = cert.quantity if(i==cert.quantity-1)
-
new_cert.preferred_payment_order = 'prepaid'
-
new_cert.save
-
cc = CertificateContent.new
-
cc.certificate_order=new_cert
-
cc.save
-
order.line_items.build :sellable=>new_cert
-
end
-
end
-
end
-
-
# used for determining which Sub Ca certs to use
-
def set_comodo_subca(params, options={})
-
cci=Settings.ca_certificate_id_dv
-
if options[:ca_certificate_id]
-
cci = options[:ca_certificate_id]
-
elsif [CA_CERTIFICATES[:SSLcomSHA2]].include? self.ca
-
cci = if Settings.send_dv_first and external_order_number.blank?
-
Settings.ca_certificate_id_dv #first time needs to be DV
-
elsif external_order_number_meta=="EV"
-
Settings.ca_certificate_id_ev
-
elsif external_order_number_meta=="OV"
-
Settings.ca_certificate_id_ov
-
elsif external_order_number_meta=="DV"
-
Settings.ca_certificate_id_dv
-
elsif certificate.is_ev?
-
Settings.ca_certificate_id_ev
-
elsif certificate.is_ov?
-
Settings.ca_certificate_id_ov
-
else
-
Settings.ca_certificate_id_dv
-
end
-
elsif certificate.serial=~/256sslcom/
-
cci = if certificate.is_ev?
-
"403"
-
elsif certificate.is_essential_ssl?
-
"401"
-
else
-
"402"
-
end
-
end
-
params.merge!('caCertificateID' => cci.to_s)
-
end
-
-
-
def self.trial_conversions(start=30.days.ago, finish=Date.today)
-
free, nonfree, result, stats, count = {}, {}, {}, [], 0
-
CertificateOrder.range(start, finish).not_test.free.map{|co|free.merge!(co.id.to_s => co.all_domains) unless co.all_domains.blank?}
-
CertificateOrder.range(start, finish).not_test.nonfree.map{|co|nonfree.merge!(co.id.to_s => co.all_domains) unless co.all_domains.blank?}
-
nonfree.each do |nk,nv|
-
free.each do |fk,fv|
-
if !(nv & fv).empty?
-
count+=1
-
co_fk = CertificateOrder.find(fk)
-
co_nk = CertificateOrder.find(nk)
-
result.merge!([co_fk.ref, 0.01*co_fk.amount, co_fk.created_at.strftime("%b %d, %Y")]=>
-
[co_nk.ref, 0.01*co_nk.amount, co_nk.created_at.strftime("%b %d, %Y")])
-
stats<<[co_fk.ref, 0.01*co_fk.amount, co_fk.created_at.strftime("%b %d, %Y"),
-
co_nk.ref, 0.01*co_nk.amount, co_nk.created_at.strftime("%b %d, %Y")].join("/")
-
free.delete fk
-
break
-
end
-
end
-
end
-
File.open("/tmp/trial_conversions.txt", "w") { |file| file.write stats.join("\n") }
-
[count,result]
-
end
-
-
end
-
class ProductVariantGroup < ActiveRecord::Base
-
has_many :product_variant_items, dependent: :destroy
-
belongs_to :variantable, :polymorphic => true, touch: true
-
validates_uniqueness_of :display_order, :scope => [:variantable_id, :variantable_type]
-
-
scope :duration, ->{where{(published_as == "live") & (title == "Duration")}}
-
scope :domains, ->{where{(published_as == "live") & (title == "Domains")}}
-
scope :server_licenses, ->{where{(published_as == 'live') & (title == "Server Licenses")}}
-
end
-
class ProductVariantItem < ActiveRecord::Base
-
extend Memoist
-
acts_as_sellable :cents => :amount, :currency => false
-
belongs_to :product_variant_group
-
has_one :sub_order_item
-
acts_as_publishable :live, :draft, :discontinue_sell
-
-
#validates_uniqueness_of :display_order, :scope => :product_variant_group_id
-
validates_presence_of :product_variant_group
-
-
def certificate
-
@pvi_certificate ||=
-
product_variant_group.variantable if
-
product_variant_group &&
-
product_variant_group.variantable &&
-
product_variant_group.variantable.is_a?(Certificate)
-
end
-
memoize :certificate
-
-
def cached_certificate_id
-
Rails.cache.fetch("#{cache_key}/cached_certificate_id") do
-
certificate.id if certificate
-
end
-
end
-
-
def is_domain?
-
item_type=='ucc_domain'
-
end
-
-
def is_duration?
-
item_type=='duration'
-
end
-
-
def is_server_license?
-
item_type=='server_license'
-
end
-
-
def reseller_tier_of?(compare)
-
if serial =~(/tr\z/)
-
compare.serial==base_serial
-
end
-
end
-
-
def reseller_tier_label
-
serial.slice(/.+(?=(\d)tr)/) || serial.slice(/.+(?=(\-\w+?)tr)/)
-
$1
-
end
-
-
private
-
-
# A one time method to add wildcard domains as a separate charge item
-
def self.add_wildcards_to_ucc
-
tier_discounts = [1, 0.80, 0.75, 0.7, 0.6]
-
prices = {ucc: 12900, evucc: 19900}
-
out=[]
-
Certificate.where{product =~ '%ucc%'}.flatten.map(&:product_variant_groups).
-
flatten.find_all{|d|d.title=="Domains"}.
-
flatten.map(&:product_variant_items).
-
flatten.find_all{|d|d.title =~ /4-200/}.each do |pvi|
-
#replace 'adm' with 'wcdm' in serial
-
serial = pvi.serial.gsub "adm", "wcdm"
-
pvi.serial =~ /(\d)tr\z/
-
tier=$1
-
type = pvi.serial =~ /ev/ ? :evucc : :ucc
-
pvi.title =~ /\A(\d)/
-
duration = $1
-
amount = prices[type] * duration.to_i * (tier ? tier_discounts[tier.to_i-1] : 1)
-
if type == :ucc #there is no evucc wildcard but kept the logic anyway
-
ProductVariantItem.create amount: amount.round(2).to_i, serial: serial, title: "each #{duration} Year Wildcard Domain", description: "each #{duration} Year Wildcard Domain".downcase,
-
text_only_description: "each #{duration} Year Wildcard Domain".downcase, display_order: duration,
-
product_variant_group_id: pvi.product_variant_group_id, status: pvi.status, item_type: pvi.item_type,
-
value: pvi.value, published_as: pvi.published_as
-
end
-
end
-
out
-
end
-
-
# remove reseller_tier
-
def base_serial
-
serial.slice(/.+(?=\-.+?tr)/) || serial.slice(/.+(?=\dtr)/)
-
end
-
-
-
end
-
class Receipt < ActiveRecord::Base
-
belongs_to :order
-
-
serialize :confirmation_recipients
-
serialize :receipt_recipients
-
serialize :processed_recipients
-
end
-
class Refund < ActiveRecord::Base
-
include ActiveMerchant::Billing
-
-
belongs_to :order
-
belongs_to :order_transaction
-
belongs_to :user
-
-
serialize :merchant_response
-
-
scope :failed, -> {where(status: 'failed')}
-
scope :successful, -> {where(status: 'success')}
-
-
def self.refund_merchant(params)
-
refund = Refund.new
-
case params[:merchant]
-
when 'stripe'
-
refund.stripe_refund(params)
-
when 'authnet'
-
unsettled = refund.unsettled_transaction?(params)
-
unsettled ? refund.authnet_void(params) : refund.authnet_refund(params)
-
when 'paypal'
-
refund.paypal_refund(params)
-
end
-
refund.duplicate_refund if refund.persisted?
-
refund
-
end
-
-
def stripe_refund(params)
-
stripe_params = {
-
charge: get_reference(params),
-
amount: params[:amount],
-
metadata: {
-
reason: params[:reason],
-
requested_amount: params[:amount],
-
user_id: params[:user_id],
-
order_id: params[:order].id,
-
order_trans_id: params[:order_transaction].id
-
}
-
}
-
begin
-
refund = Stripe::Refund.create(stripe_params)
-
rescue Stripe::CardError,
-
Stripe::RateLimitError,
-
Stripe::InvalidRequestError,
-
Stripe::AuthenticationError,
-
Stripe::APIConnectionError,
-
Stripe::StripeError => e
-
log_stripe_failure_response(e, params)
-
else
-
log_stripe_success_response(refund, params)
-
end
-
end
-
-
def authnet_refund(params)
-
response = authnet_gateway.refund(params[:amount], get_reference(params))
-
update_from_response(params, response)
-
end
-
-
def authnet_void(params)
-
# unsettled transaction, try void if purchse was made within 24 hours.
-
response = authnet_gateway.void(get_reference(params))
-
update_from_response(params, response)
-
end
-
-
def paypal_refund(params)
-
response = paypal_gateway.refund(params[:amount], get_reference(params))
-
update_from_response(params, response)
-
end
-
-
def unsettled_transaction?(params)
-
end_time = Time.parse(DateTime.now.to_s)
-
start_time = Time.parse(params[:order].created_at.to_s)
-
((end_time - start_time)/3600) <= 24
-
end
-
-
def successful?
-
status == 'success'
-
end
-
-
def duplicate_refund
-
# If another order was deducted from this order (e.g.: Deposit), create a refund
-
# record for both orders.
-
found = Order.where(deducted_from_id: order.id)
-
if self.persisted? && found.any?
-
copy = self.dup
-
copy.update(order_id: found.last.id)
-
end
-
end
-
-
private
-
-
def get_reference(params)
-
merchant = params[:merchant]
-
return params[:order].notes.split.last.strip.delete('#paidviapaypal') if merchant == 'paypal'
-
return params[:order_transaction].reference if %w{stripe authnet}.include?(merchant)
-
end
-
-
def parse_main_params(params)
-
{
-
merchant: params[:merchant],
-
amount: params[:amount],
-
user_id: params[:user_id],
-
order_transaction: params[:order_transaction],
-
order: params[:order],
-
reason: params[:reason],
-
partial_refund: partial_refund?(params)
-
}
-
end
-
-
def partial_refund?(params)
-
amt = params[:order_transaction] ? params[:order_transaction] : params[:order]
-
params[:amount] < amt.cents
-
end
-
#
-
# Stripe Helpers
-
#
-
def log_stripe_failure_response(e, params)
-
self.update(
-
parse_main_params(params).merge({
-
status: 'failed',
-
message: e.to_param,
-
merchant_response: {
-
stripe_charge_id: get_reference(params),
-
stripe_request_id: e.request_id,
-
stripe_error_class: e.class.to_s,
-
stripe_error_type: e.json_body[:error][:type],
-
stripe_error_message: e.to_param
-
}
-
})
-
)
-
end
-
-
def log_stripe_success_response(refund, params)
-
if refund.status == 'succeeded'
-
self.update(
-
parse_main_params(params).merge({
-
status: 'success',
-
reference: refund.id,
-
merchant_response: refund.to_hash
-
})
-
)
-
end
-
end
-
#
-
# ActiveMerchant Helpers
-
#
-
def update_from_response(params, response)
-
if response.success?
-
log_success_response(params, response)
-
else
-
log_failure_response(params, response)
-
end
-
end
-
-
def log_success_response(params, response)
-
if response.success?
-
self.update(
-
parse_main_params(params).merge({
-
status: 'success',
-
reference: response.authorization,
-
merchant_response: response.params,
-
test: response.test
-
})
-
)
-
end
-
end
-
-
def log_failure_response(params, response)
-
unless response.success?
-
self.update(
-
parse_main_params(params).merge({
-
status: 'failed',
-
message: response.message,
-
merchant_response: response.params,
-
test: response.test
-
})
-
)
-
end
-
end
-
-
def paypal_gateway
-
s = ::Rails.application.secrets
-
ActiveMerchant::Billing::PaypalExpressGateway.new(
-
login: s.paypal_username,
-
password: s.paypal_password,
-
signature: s.paypal_signature
-
)
-
end
-
-
def authnet_gateway
-
s = ::Rails.application.secrets
-
ActiveMerchant::Billing::AuthorizeNetGateway.new(
-
login: s.authorize_net_key,
-
password: s.authorize_net_trans_id
-
)
-
end
-
end
-
class RegisteredAgent < ActiveRecord::Base
-
belongs_to :ssl_account
-
belongs_to :requester, :class_name => 'User'
-
belongs_to :approver, :class_name => 'User'
-
has_many :managed_certificates, dependent: :destroy
-
-
attr_accessor :api_status, :reason
-
-
# will_paginate
-
cattr_accessor :per_page
-
@@per_page = 10
-
-
scope :search_with_terms, lambda { |term|
-
term ||= ""
-
term = term.strip.split(/\s(?=(?:[^']|'[^']*')*$)/)
-
filters = { mac_address: nil, friendly_name: nil, ref: nil, subject: nil, sans: nil,
-
effective_date: nil, expiration_date: nil }
-
-
filters.each {|fn, fv|
-
term.delete_if { |s| s =~ Regexp.new(fn.to_s+"\\:\\'?([^']*)\\'?"); filters[fn] ||= $1; $1 }
-
}
-
term = term.empty? ? nil : term.join(" ")
-
-
return nil if [term, *(filters.values)].compact.empty?
-
-
result = self.all
-
unless term.blank?
-
result = case term
-
when /sm-\w/i
-
result.where {
-
ref =~ "%#{term}%"
-
}
-
else
-
result.where {
-
(ip_address =~ "%#{term}%") |
-
(mac_address =~ "%#{term}%") |
-
(agent =~ "%#{term}%") |
-
(friendly_name =~ "%#{term}%") |
-
(workflow_status =~ "%#{term}%") |
-
(managed_certificates.common_name =~ "%#{term}%") |
-
(managed_certificates.subject_alternative_names =~ "%#{term}%")}
-
end
-
end
-
-
%w(mac_address).each do |field|
-
query = filters[field.to_sym]
-
result = result.where(mac_address: query.split(',')) if query
-
end
-
-
%w(friendly_name).each do |field|
-
query = filters[field.to_sym]
-
result = result.where{ friendly_name =~ "%#{query}%" } if query
-
end
-
-
%w(ref).each do |field|
-
query = filters[field.to_sym]
-
result = result.where(ref: query.split(',')) if query
-
end
-
-
%w(subject).each do |field|
-
query = filters[field.to_sym]
-
result = result.joins(:managed_certificates).where{ managed_certificates.common_name =~ "%#{query}%" } if query
-
end
-
-
%w(sans).each do |field|
-
query = filters[field.to_sym]
-
result = result.joins(:managed_certificates)
-
.where{ managed_certificates.subject_alternative_names =~ "%#{query}%" } if query
-
end
-
-
%w(effective_date expiration_date).each do |field|
-
query = filters[field.to_sym]
-
if query
-
query = query.split("-")
-
start = Date.strptime query[0], "%m/%d/%Y"
-
finish = query[1] ? Date.strptime(query[1], "%m/%d/%Y") : start + 1.day
-
-
if field == "effective_date"
-
result = result.joins(:managed_certificates).where{ (managed_certificates.effective_date >> (start..finish)) }
-
elsif field == "expiration_date"
-
result = result.joins(:managed_certificates).where{ (managed_certificates.expiration_date >> (start..finish)) }
-
end
-
end
-
end
-
-
result.uniq
-
}
-
-
before_create do |ra|
-
ra.ref = 'sm-' + SecureRandom.hex(1) + Time.now.to_i.to_s(32)
-
end
-
-
def to_param
-
ref
-
end
-
end
-
1
class Registrant < Contact
-
-
1
enum registrant_type: { individual: 0, organization: 1 }
-
-
1
after_save :set_default_status
-
1
after_destroy :release_dependant_contacts
-
-
1
validates_presence_of :contactable
-
1
validates_presence_of :company_name, :address1, :city, :state, :postal_code, :country,
-
if: Proc.new{|r|
-
!r.reusable? && r.contactable &&
-
r.contactable.certificate_order.certificate.requires_company_info?
-
}
-
1
validates_presence_of :phone,
-
if: Proc.new{|r|
-
!r.reusable? && r.contactable && (
-
r.contactable.certificate_order.certificate.is_code_signing? ||
-
r.contactable.certificate_order.certificate.is_client_enterprise? ||
-
r.contactable.certificate_order.certificate.is_client_business?
-
)
-
}
-
1
validates_presence_of :title,
-
if: Proc.new{|r|
-
!r.reusable? && r.contactable && (
-
r.contactable.certificate_order.certificate.is_client_enterprise? ||
-
r.contactable.certificate_order.certificate.is_client_business?
-
)
-
}
-
1
validates_presence_of :email,
-
if: Proc.new{|r|
-
!r.reusable? && r.contactable &&
-
r.contactable.certificate_order.certificate.is_code_signing?
-
}
-
1
validates_presence_of :first_name, :last_name,
-
if: Proc.new{|r|
-
!r.reusable? && r.contactable && (
-
r.contactable.certificate_order.certificate.is_client_pro? ||
-
r.contactable.certificate_order.certificate.is_code_signing? ||
-
r.contactable.certificate_order.certificate.is_client_enterprise? ||
-
r.contactable.certificate_order.certificate.is_client_business?
-
)
-
}
-
-
1
validates_presence_of :business_category, :company_number, :incorporation_country,
-
if: Proc.new{|r|
-
!r.reusable? && r.contactable && r.contactable.certificate_order.certificate.is_ev?
-
}
-
-
1
validates :city, :state, :country, :email, presence: true,
-
if: proc { |r| r.reusable? && (r.organization? || r.individual?) }
-
1
validates :company_name, :phone, presence: true, if: proc { |r| r.reusable? && r.organization? }
-
1
validates :first_name, :last_name, presence: true, if: proc { |r| r.reusable? && r.individual? }
-
-
1
before_validation :set_default_title
-
1
after_save :set_one_epki_agreement
-
-
1
def applies_to_certificate_order?(certificate_order)
-
domains.any? do |domain|
-
if certificate_order.certificate.is_smime_or_client?
-
email_in_subdomain?(certificate_order.get_recipient.email, domain)
-
end
-
end unless domains.blank?
-
end
-
-
1
protected
-
-
1
def set_default_status
-
if reusable? && status.nil?
-
self.in_progress!
-
end
-
end
-
-
1
def reusable?
-
contactable.is_a?(SslAccount)
-
end
-
-
1
def self.get_validated_registrants(team)
-
Registrant.where(
-
contactable_type: team.class,
-
contactable_id: team.id,
-
status: statuses[:validated]
-
)
-
end
-
-
1
def filter_approved_domains(filter_domains)
-
approved = []
-
filter_domains.any? do |filter_domain|
-
domains.any? do |domain|
-
if email_in_subdomain?(filter_domain, domain)
-
approved << filter_domain
-
end
-
end
-
end
-
approved
-
end
-
-
1
def filter_pending_domains(filter_domains)
-
filter_domains - filter_approved_domains(filter_domains)
-
end
-
-
1
private
-
-
1
def set_default_title
-
self.title = 'Mr' if title.blank?
-
end
-
-
1
def set_one_epki_agreement
-
if epki_agreement? && contactable.is_a?(SslAccount)
-
other_epki = contactable.all_saved_contacts
-
.where.not(id: self.id)
-
.where(status: Contact::statuses[:epki_agreement])
-
other_epki.update(:status, Contact::statuses[:validated]) if other_epki.any?
-
end
-
end
-
-
1
def email_in_subdomain?(target_email, compare_with)
-
DomainControlValidation.domain_in_subdomains?(
-
target_email.split('@').last, compare_with
-
)
-
end
-
-
1
def release_dependant_contacts
-
Contact.where(parent_id: id).update_all(parent_id: nil)
-
end
-
end
-
1
class ReminderTrigger < ActiveRecord::Base
-
end
-
class RenewalAttempt < ActiveRecord::Base
-
belongs_to :certificate_order
-
belongs_to :order_transaction
-
end
-
class RenewalNotification < ActiveRecord::Base
-
belongs_to :certificate_order
-
end
-
class ReprocessCertificateOrder < Order
-
-
end
-
class RequestToken < OauthToken
-
-
attr_accessor :provided_oauth_verifier
-
-
def authorize!(user)
-
return false if authorized?
-
self.user = user
-
self.authorized_at = Time.now
-
self.verifier=OAuth::Helper.generate_key(20)[0,20] unless oauth10?
-
self.save
-
end
-
-
def exchange!
-
return false unless authorized?
-
return false unless oauth10? || verifier==provided_oauth_verifier
-
-
RequestToken.transaction do
-
access_token = AccessToken.create(:user => user, :client_application => client_application)
-
invalidate!
-
access_token
-
end
-
end
-
-
def to_query
-
if oauth10?
-
super
-
else
-
"#{super}&oauth_callback_confirmed=true"
-
end
-
end
-
-
def oob?
-
callback_url.nil? || callback_url.downcase == 'oob'
-
end
-
-
def oauth10?
-
(defined? OAUTH_10_SUPPORT) && OAUTH_10_SUPPORT && self.callback_url.blank?
-
end
-
-
end
-
1
class Reseller < ActiveRecord::Base
-
1
belongs_to :ssl_account
-
1
has_many :orders, through: :ssl_account
-
1
belongs_to :reseller_tier
-
1
easy_roles :roles
-
-
1
attr_protected :reseller_tier
-
1
PROFILE_COLUMNS = %w(display_name tagline description)
-
1
COMPANY_COLUMNS = %w(organization website address1 address2 address3
-
postal_code city state country)
-
1
ADMIN_COLUMNS = %w(first_name last_name email phone ext fax)
-
1
PAYMENT_COLUMNS = %w(tax_number)
-
1
NONREQUIRED_COLUMNS = %w(ext fax)
-
1
REQUIRED_COLUMNS = %w(type_organization organization website address1
-
postal_code city state country) + ADMIN_COLUMNS -
-
NONREQUIRED_COLUMNS
-
1
FORM_COLUMNS=%w(type_organization)+ADMIN_COLUMNS+COMPANY_COLUMNS
-
1
BUSINESS = "business"
-
1
INDIVIDUAL = "individual"
-
-
1
WELCOME="Welcome to the SSL.com Reseller Program!"
-
-
TEMP_FIELDS = {
-
1
first_name: "first name",
-
last_name: "last name",
-
email: "changeto@email.com",
-
phone: "123-456-7890",
-
type_organization: "business",
-
organization: "Some organization name",
-
website: "change.to.website",
-
address1: "Some Address",
-
postal_code: "Some postal code",
-
city: "Some city",
-
state: "Some state",
-
tax_number: "Some tax number",
-
country: "US"
-
}
-
-
1
SUBDOMAIN = 'reseller'
-
-
1
TARGETED = %w(host_providers registrars merchants enterprises government
-
education medical) - %w(enterprises government
-
education medical)
-
-
1
SIGNUP_PAGES = %w(Reseller\ Profile Select\ Tier Billing\ Information Registration\ Complete)
-
1
SIGNUP_PAGES_FREE = %w(Reseller\ Profile Select\ Tier Registration\ Complete)
-
-
1
validates_presence_of *((REQUIRED_COLUMNS-%w(email organization state)).map(&:intern))
-
1
validates_presence_of :organization, :if => Proc.new{|reseller| reseller.type_organization == BUSINESS }
-
1
validates_length_of *((FORM_COLUMNS).map(&:intern)+[:maximum => 100])
-
1
validates_length_of :email, :within => 3..100
-
1
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9A-Z]+\.)+[a-zA-Z]{2,})\z/
-
1
validates_presence_of "state", :if => Proc.new{|x| x.american? }
-
-
1
include Workflow
-
1
workflow do
-
1
state :new do
-
1
event :profile_submitted, :transitions_to => :select_tier
-
1
event :back, :transitions_to => :new
-
1
event :completed, :transitions_to => :complete
-
end
-
-
1
state :select_tier do
-
1
event :tier_selected, :transitions_to => :enter_billing_information
-
1
event :completed, :transitions_to => :complete
-
1
event :back, :transitions_to => :new
-
end
-
-
1
state :enter_billing_information do
-
1
event :completed, :transitions_to => :complete
-
1
event :back, :transitions_to => :select_tier
-
end
-
-
1
state :complete
-
end
-
-
1
def american?
-
country == "United States"
-
end
-
-
1
def type_organization
-
read_attribute("type_organization") || BUSINESS
-
end
-
-
# the final stage of reseller signup
-
1
def finish_signup(tier)
-
self.reseller_tier = tier
-
self.completed!
-
ssl_account.remove_role! 'new_reseller'
-
ssl_account.add_role! 'reseller'
-
end
-
-
end
-
class ResellerTier < ActiveRecord::Base
-
include PriceView
-
acts_as_sellable :cents => :amount, :currency => false
-
has_many :certificates, dependent: :destroy
-
has_many :product_variant_groups, through: :certificates
-
has_many :product_variant_items, through: :certificates
-
has_many :resellers
-
serialize :description
-
-
DEFAULT_TIER = 2
-
PUBLIC_TIERS = [7,8,*(1..5)]
-
TIER_KEY = :r_tier_102019
-
-
# these tiers are for sale to the general public, otherwise the tier is customized and private to select resellers
-
scope :general, ->{where{id>>PUBLIC_TIERS}}
-
-
def self.sitemap
-
ResellerTier.general
-
end
-
-
# this method creates the tier, products and adds the reseller.
-
# options[:label] - the name of the tier. If it already exists, then this method will modify this tier
-
# options[:products] - **not done** list of certificate or products and pricing to create (ie for certificate_id 100 at $33.50 - {100: "33.50"})
-
# options[:reseller_ids] - array of resellers to include into this tier
-
# options[:amount]- (optional) deposit buy-in
-
# options[:roles]- (optional) role label
-
# options[:discount_rate] - discount rate on all items.
-
# example - ResellerTier.generate_tier(label: "custom", description: {"name": "bob's tier"}, reseller_ids:[Reseller.last.id], discount_rate: 0.5)
-
# ResellerTier.generate_tier(label: "7", description: {"ideal_for"=> "enterprise organizations"}, discount_rate: 0.35, amount: 5000000, roles: "tier_7_reseller")
-
# ResellerTier.generate_tier(label: "6", description: {"ideal_for"=> "enterprise organizations"}, discount_rate: 0.5, amount: 3500000, roles: "tier_6_reseller")
-
# ResellerTier.generate_tier(label: "ansonnet", description: {:name=>"ansonnet tier"}, discount_rate: 0.315)
-
# ResellerTier.generate_tier(label: "dtntcomodoca", description: {:name=>"dtnt comodoca tier"}, discount_rate: 0.167)
-
def self.generate_tier(options)
-
tier = find_or_create_by(label: options[:label])
-
tier.description = options[:description]
-
tier.published_as = "live"
-
tier.amount = options[:amount]
-
tier.roles = options[:roles]
-
tier.save!
-
options[:reseller_ids].each do |id|
-
tier.resellers << Reseller.find(id)
-
end if options[:reseller_ids]
-
Certificate.base_products.available.each do |cert|
-
tier.certificates << cert.duplicate(discount_rate: options[:discount_rate], reseller_tier_label: options[:label],
-
amount: options[:amount], roles: options[:roles])
-
end
-
end
-
-
def price=(amount)
-
self.amount = amount.gsub(/\./,"").to_i
-
end
-
-
def is_free?
-
amount <= 0
-
end
-
-
def self.tier_suffix(label)
-
"#{'-' unless (label =~/\A(\d)\z/ and $1.to_i < 6)}"+label + 'tr' #add '-' for non single digit tier due to flexible labeling
-
end
-
-
def to_param
-
id.to_s
-
end
-
-
# sample commands to create a new tier and update pricing
-
#
-
# label="dtntcomodoca"
-
# rt=ResellerTier.generate_tier(label: label, description: {:name=>"#{label} tier"}, discount_rate: 0.167)
-
# rt=ResellerTier.find_by_label(label)
-
# rt.prices_matrix
-
# options= {11108=>["Enterprise EV Multi-domain UCC SSL", "Domains", "1 Year Domain For 3 Domains (ea domain)", 5000],
-
# 11109=>["Enterprise EV Multi-domain UCC SSL", "Domains", "1 Year Domain For Domains 4-200 (ea domain)", 5000],
-
# 11110=>["Enterprise EV Multi-domain UCC SSL", "Domains", "2 Year Domain For 3 Domains (ea domain)", 10000],
-
# 11111=>["Enterprise EV Multi-domain UCC SSL", "Domains", "2 Year Domain For Domains 4-200 (ea domain)", 10000],
-
# 11112=>["Enterprise EV Multi-domain UCC SSL", "Server Licenses", "1 Year Additional Server License", 167],
-
# 11113=>["Enterprise EV Multi-domain UCC SSL", "Server Licenses", "2 Years Additional Server License", 301],
-
# 11114=>["Multi-domain UCC SSL", "Domains", "1 Year Domain For 3 Domains (ea domain)", 750],
-
# 11115=>["Multi-domain UCC SSL", "Domains", "1 Year Domain For Domains 4-200 (ea domain)", 750],
-
# 11116=>["Multi-domain UCC SSL", "Domains", "2 Year Domain For 3 Domains (ea domain)", 1350],
-
# 11117=>["Multi-domain UCC SSL", "Domains", "2 Year Domain For Domains 4-200 (ea domain)", 1350],
-
# 11118=>["Multi-domain UCC SSL", "Domains", "3 Year Domain For 3 Domains (ea domain)", 1950],
-
# 11119=>["Multi-domain UCC SSL", "Domains", "3 Year Domain For Domains 4-200 (ea domain)", 1950],
-
# 11120=>["Multi-domain UCC SSL", "Domains", "4 Year Domain For 3 Domains (ea domain)", 2550],
-
# 11121=>["Multi-domain UCC SSL", "Domains", "4 Year Domain For Domains 4-200 (ea domain)", 2550],
-
# 11122=>["Multi-domain UCC SSL", "Domains", "5 Year Domain For 3 Domains (ea domain)", 3150],
-
# 11123=>["Multi-domain UCC SSL", "Domains", "5 Year Domain For Domains 4-200 (ea domain)", 3150],
-
# 11124=>["Multi-domain UCC SSL", "Domains", "each 1 Year Wildcard Domain", 5000],
-
# 11125=>["Multi-domain UCC SSL", "Domains", "each 2 Year Wildcard Domain", 10000],
-
# 11126=>["Multi-domain UCC SSL", "Domains", "each 3 Year Wildcard Domain", 15000],
-
# 11127=>["Multi-domain UCC SSL", "Domains", "each 4 Year Wildcard Domain", 20000],
-
# 11128=>["Multi-domain UCC SSL", "Domains", "each 5 Year Wildcard Domain", 25000],
-
# 11129=>["Multi-domain UCC SSL", "Server Licenses", "1 Year Additional Server License", 167],
-
# 11130=>["Multi-domain UCC SSL", "Server Licenses", "2 Years Additional Server License", 301],
-
# 11131=>["Multi-domain UCC SSL", "Server Licenses", "3 Years Additional Server License", 426],
-
# 11132=>["Multi-domain UCC SSL", "Server Licenses", "4 Years Additional Server License", 535],
-
# 11133=>["Multi-domain UCC SSL", "Server Licenses", "5 Years Additional Server License", 627],
-
# 11134=>["Enterprise EV SSL", "Duration", "1 Year", 10000],
-
# 11135=>["Enterprise EV SSL", "Duration", "2 Years", 18000],
-
# 11136=>["High Assurance SSL", "Duration", "1 Year", 1000],
-
# 11137=>["High Assurance SSL", "Duration", "2 Years", 1800],
-
# 11138=>["High Assurance SSL", "Duration", "3 Years", 2600],
-
# 11139=>["High Assurance SSL", "Duration", "4 Years", 3400],
-
# 11140=>["High Assurance SSL", "Duration", "5 Years", 4200],
-
# 11141=>["Free SSL", "Duration", "90 Days", 0],
-
# 11142=>["Multi-subdomain Wildcard SSL", "Duration", "1 Year", 5000],
-
# 11143=>["Multi-subdomain Wildcard SSL", "Duration", "2 Years", 10000],
-
# 11144=>["Multi-subdomain Wildcard SSL", "Duration", "3 Years", 15000],
-
# 11145=>["Multi-subdomain Wildcard SSL", "Duration", "4 Years", 20000],
-
# 11146=>["Multi-subdomain Wildcard SSL", "Duration", "5 Years", 25000],
-
# 11147=>["Multi-subdomain Wildcard SSL", "Server Licenses", "1 Year Additional Server License", 167],
-
# 11148=>["Multi-subdomain Wildcard SSL", "Server Licenses", "2 Years Additional Server License", 301],
-
# 11149=>["Multi-subdomain Wildcard SSL", "Server Licenses", "3 Years Additional Server License", 426],
-
# 11150=>["Multi-subdomain Wildcard SSL", "Server Licenses", "4 Years Additional Server License", 535],
-
# 11151=>["Multi-subdomain Wildcard SSL", "Server Licenses", "5 Years Additional Server License", 627],
-
# 11152=>["Premium Multi-subdomain SSL", "Domains", "1 Year Domain For 3 Domains (ea domain)", 552],
-
# 11153=>["Premium Multi-subdomain SSL", "Domains", "1 Year Domain For Domains 4-200 (ea domain)", 819],
-
# 11154=>["Premium Multi-subdomain SSL", "Domains", "2 Year Domain For 3 Domains (ea domain)", 992],
-
# 11155=>["Premium Multi-subdomain SSL", "Domains", "2 Year Domain For Domains 4-200 (ea domain)", 1473],
-
# 11156=>["Premium Multi-subdomain SSL", "Domains", "3 Year Domain For 3 Domains (ea domain)", 1406],
-
# 11157=>["Premium Multi-subdomain SSL", "Domains", "3 Year Domain For Domains 4-200 (ea domain)", 2087],
-
# 11158=>["Premium Multi-subdomain SSL", "Domains", "4 Year Domain For 3 Domains (ea domain)", 1764],
-
# 11159=>["Premium Multi-subdomain SSL", "Domains", "4 Year Domain For Domains 4-200 (ea domain)", 2717],
-
# 11160=>["Premium Multi-subdomain SSL", "Domains", "5 Year Domain For 3 Domains (ea domain)", 2067],
-
# 11161=>["Premium Multi-subdomain SSL", "Domains", "5 Year Domain For Domains 4-200 (ea domain)", 3274],
-
# 11162=>["Premium Multi-subdomain SSL", "Server Licenses", "1 Year Additional Server License", 167],
-
# 11163=>["Premium Multi-subdomain SSL", "Server Licenses", "2 Years Additional Server License", 301],
-
# 11164=>["Premium Multi-subdomain SSL", "Server Licenses", "3 Years Additional Server License", 426],
-
# 11165=>["Premium Multi-subdomain SSL", "Server Licenses", "4 Years Additional Server License", 535],
-
# 11166=>["Premium Multi-subdomain SSL", "Server Licenses", "5 Years Additional Server License", 627],
-
# 11167=>["Basic SSL", "Duration", "1 Year", 750],
-
# 11168=>["Basic SSL", "Duration", "2 Years", 1350],
-
# 11169=>["Basic SSL", "Duration", "3 Years", 1950],
-
# 11170=>["Basic SSL", "Duration", "4 Years", 2550],
-
# 11171=>["Basic SSL", "Duration", "5 Years", 3150],
-
# 11172=>["Code Signing", "Duration", "1 Year", 2155],
-
# 11173=>["Code Signing", "Duration", "2 Years", 3878],
-
# 11174=>["Code Signing", "Duration", "3 Years", 5494],
-
# 11175=>["Code Signing", "Duration", "4 Years", 6894],
-
# 11176=>["Code Signing", "Duration", "5 Years", 8079],
-
# 11177=>["Code Signing", "Duration", "6 Years", 9049],
-
# 11178=>["Code Signing", "Duration", "7 Years", 9803],
-
# 11179=>["Code Signing", "Duration", "8 Years", 10341],
-
# 11180=>["Code Signing", "Duration", "9 Years", 10664],
-
# 11181=>["Code Signing", "Duration", "10 Years", 10772],
-
# 11182=>["EV Code Signing", "Duration", "1 Year", 13000],
-
# 11183=>["EV Code Signing", "Duration", "2 Years", 24000],
-
# 11184=>["EV Code Signing", "Duration", "3 Years", 31000],
-
# 11185=>["Personal Basic", "Duration", "1 Year", 750],
-
# 11186=>["Personal Basic", "Duration", "2 Years", 1350],
-
# 11187=>["Personal Basic", "Duration", "3 Years", 1950],
-
# 11188=>["Personal Business", "Duration", "1 Year", 1503],
-
# 11189=>["Personal Business", "Duration", "2 Years", 2005],
-
# 11190=>["Personal Business", "Duration", "3 Years", 2505],
-
# 11191=>["Personal Pro", "Duration", "1 Year", 1169],
-
# 11192=>["Personal Pro", "Duration", "2 Years", 1336],
-
# 11193=>["Personal Pro", "Duration", "3 Years", 1503],
-
# 11194=>["Personal Enterprise", "Duration", "1 Year", 4159],
-
# 11195=>["Personal Enterprise", "Duration", "2 Years", 8334],
-
# 11196=>["Personal Enterprise", "Duration", "3 Years", 10004],
-
# 11197=>["Document Signing", "Duration", "1 Years", 5829],
-
# 11198=>["Document Signing", "Duration", "2 Years", 10839],
-
# 11199=>["Document Signing", "Duration", "3 Years", 14179],
-
# 11200=>["NAESB Basic", "Duration", "1 Years", 1253],
-
# 11201=>["NAESB Basic", "Duration", "2 Years", 2505]}
-
# rt.update_prices(options)
-
# sa = SslAccount.find_by_acct_number "a0a-1dpi0uq"
-
# sa.adjust_reseller_tier label
-
# bundle exec rake cas:seed_ejbca_profiles LIVE=all EJBCA_ENV=production RAILS_ENV=production # create mappings
-
end
-
class Revocation < ActiveRecord::Base
-
belongs_to :revoked_signed_certificate, class_name: "SignedCertificate", foreign_key: "revoked_signed_certificate_id"
-
belongs_to :replacement_signed_certificate, class_name: "SignedCertificate", foreign_key: "replacement_signed_certificate_id"
-
-
def revoked_signed_certificate
-
if read_attribute(:revoked_signed_certificate_id).blank?
-
return nil if fingerprint.blank?
-
sc=SignedCertificate.find_by_fingerprint(fingerprint)
-
unless sc.blank?
-
write_attribute(:revoked_signed_certificate_id, sc.id)
-
save(validate: false)
-
sc
-
end
-
else
-
SignedCertificate.find(read_attribute(:revoked_signed_certificate_id))
-
end
-
end
-
-
def replacement_signed_certificate
-
if read_attribute(:replacement_signed_certificate_id).blank?
-
return nil if replacement_fingerprint.blank?
-
sc=SignedCertificate.find_by_fingerprint(replacement_fingerprint)
-
unless sc.blank?
-
write_attribute(:replacement_signed_certificate_id, sc.id)
-
save(validate: false)
-
sc
-
end
-
else
-
SignedCertificate.find(read_attribute(:replacement_signed_certificate_id))
-
end
-
end
-
-
def self.load_revocations(file_name)
-
File.open(file_name, "r").each_line do |line|
-
data=line.split(",")
-
revocation=Revocation.find_or_initialize_by(fingerprint: data[0].downcase)
-
next if revocation.status=="replacement_issued" or (revocation.status.blank? and !revocation.new_record?)
-
attr={}
-
sc=SignedCertificate.find_by_fingerprint(data[0].downcase)
-
if sc and sc.csr.certificate_content
-
attr.merge!({revoked_signed_certificate_id: sc.id, status: "revoke_cert_found"})
-
replacement_cert=revocation.replacement_signed_certificate ||
-
sc.csr.get_ejbca_certificate(data[1].gsub(/\n\z/,''))
-
if replacement_cert
-
attr.merge!({replacement_fingerprint: replacement_cert.fingerprint.downcase,
-
replacement_signed_certificate_id: replacement_cert.id,
-
status: "replacement_issued"})
-
end
-
end
-
Revocation.find_or_initialize_by(fingerprint: data[0].downcase).update_attributes(attr)
-
end
-
end
-
end
-
class RevocationNotification < ActiveRecord::Base
-
serialize :fingerprints
-
-
def self.load_revocations
-
# get hash of {email: [to_be_revoked_signed_certificates, replacement_signed_certificates]}
-
notifications={}
-
Revocation.find_each do |revocation|
-
sc=SignedCertificate.find_by_fingerprint(revocation.fingerprint.downcase)
-
next if sc.blank?
-
cc=sc.certificate_content
-
next if cc.blank?
-
cc.emergency_contact_emails.each {|email|
-
fingerprint=[revocation.fingerprint,revocation.replacement_fingerprint]
-
notifications[email] ||= RevocationNotification.find_or_initialize_by(email: email)
-
notifications[email].fingerprints ||= []
-
notifications[email].status ||= "loaded"
-
notifications[email].fingerprints << fingerprint unless notifications[email].fingerprints.include?(fingerprint)
-
notifications[email].save
-
}
-
# get all account admin contacts and certificate_order contacts into the hash
-
end
-
end
-
-
def self.send_serial_number_entropy_notifications
-
RevocationNotification.find_each do |rn|
-
OrderNotifier.serial_number_entropy(rn).deliver
-
rn.update_column :status, rn.status+"+2nd serial number entropy on 04/02/2019"
-
end
-
end
-
end
-
1
class Role < ActiveRecord::Base
-
1
has_many :assignments, dependent: :destroy
-
1
has_many :users, :through => :assignments
-
1
has_and_belongs_to_many :permissions
-
1
belongs_to :ssl_account
-
-
1
ACCOUNT_ADMIN = 'account_admin'
-
1
BILLING = 'billing'
-
1
INSTALLER = 'installer'
-
1
OWNER = 'owner'
-
1
RESELLER = 'reseller'
-
1
SUPER_USER = 'super_user'
-
1
SYS_ADMIN = 'sysadmin'
-
1
USERS_MANAGER = 'users_manager'
-
1
VALIDATIONS = 'validations'
-
1
RA_ADMIN = 'ra_admin'
-
1
INDIVIDUAL_CERTIFICATE = 'individual_certificate'
-
-
1
def self.get_role_id(role_name)
-
1015
Rails.cache.fetch(["get_role_id",role_name]) { Role.find_by(name: role_name).id }
-
end
-
-
1
def self.get_role_ids(role_names)
-
4
Rails.cache.fetch(["get_role_ids",role_names.join("_")]) {
-
Role.where(name: role_names).ids.uniq.reject(&:blank?).compact
-
}
-
end
-
-
1
def self.admin_role_ids
-
Role.get_role_ids([SYS_ADMIN, SUPER_USER, OWNER, RA_ADMIN])
-
end
-
-
1
def self.get_account_admin_id
-
249
Role.get_role_id(Role::ACCOUNT_ADMIN)
-
end
-
-
1
def self.get_owner_id
-
230
Role.get_role_id(Role::OWNER)
-
end
-
-
1
def self.get_reseller_id
-
Role.get_role_id(Role::RESELLER)
-
end
-
-
1
def self.get_individual_certificate_id
-
Role.get_role_id(Role::INDIVIDUAL_CERTIFICATE)
-
end
-
-
1
def self.get_select_ids_for_owner
-
3
Role.get_role_ids([
-
ACCOUNT_ADMIN,
-
BILLING,
-
INSTALLER,
-
VALIDATIONS,
-
USERS_MANAGER,
-
INDIVIDUAL_CERTIFICATE
-
])
-
end
-
-
1
def self.can_auto_add_users
-
Role.get_role_ids([
-
ACCOUNT_ADMIN,
-
OWNER,
-
RESELLER
-
])
-
end
-
-
1
def self.can_manage_users
-
1
Role.get_role_ids([
-
ACCOUNT_ADMIN,
-
OWNER,
-
RESELLER,
-
SUPER_USER,
-
SYS_ADMIN,
-
USERS_MANAGER
-
])
-
end
-
-
1
def self.can_manage_billing
-
Role.get_role_ids([
-
ACCOUNT_ADMIN,
-
BILLING,
-
OWNER,
-
RESELLER,
-
SUPER_USER,
-
SYS_ADMIN
-
])
-
end
-
-
1
def self.can_manage_payable_invoice
-
Role.get_role_ids([
-
ACCOUNT_ADMIN,
-
BILLING,
-
OWNER,
-
RESELLER
-
])
-
end
-
#
-
# Roles that cannot be managed by users_manager role
-
#
-
1
def self.cannot_be_managed
-
Role.get_role_ids([
-
ACCOUNT_ADMIN,
-
OWNER,
-
RESELLER,
-
SUPER_USER,
-
SYS_ADMIN,
-
USERS_MANAGER,
-
RA_ADMIN
-
])
-
end
-
-
1
def self.cannot_be_invited
-
Role.get_role_ids([
-
OWNER,
-
RESELLER,
-
SUPER_USER,
-
SYS_ADMIN,
-
RA_ADMIN
-
])
-
end
-
end
-
class Sandbox < Website
-
def self.exists?(domain)
-
Rails.cache.fetch("Sandbox.exists/#{domain}", expires_in: 24.hours) {
-
!self.where{(host == domain) | (api_host == domain)}.blank?
-
}
-
end
-
end
-
class ScanLog < ActiveRecord::Base
-
belongs_to :notification_group
-
belongs_to :scanned_certificate
-
-
# will_paginate
-
cattr_accessor :per_page
-
@@per_page = 10
-
end
-
class ScannedCertificate < ActiveRecord::Base
-
include CertificateProperties
-
end
-
class Schedule < ActiveRecord::Base
-
belongs_to :notification_group
-
end
-
class SentReminder < ActiveRecord::Base
-
serialize :trigger_value
-
-
validates :signed_certificate_id, :uniqueness=>
-
{:scope=>[:trigger_value,:expires_at]}
-
end
-
class ServerSoftware < ActiveRecord::Base
-
has_many :certificate_contents
-
has_many :certificate_orders, through: :certificate_contents
-
-
OTHER="1"
-
-
def self.listing
-
all.map{|s|[s.id, s.title]}
-
end
-
end
-
class ShadowSignedCertificate < SignedCertificate
-
end
-
#li - number of licenses
-
#q - quantity
-
#do - domains
-
#pr - product code
-
#rn - renewal order
-
#du - duration
-
class ShoppingCart < ActiveRecord::Base
-
belongs_to :user
-
-
LICENSES = "li"
-
QUANTITY = "q"
-
DOMAINS = "do"
-
DURATION = "du"
-
PRODUCT_CODE = "pr"
-
SUB_PRODUCT_CODE = "spr" # array of sub products that will be added through the sub_order_item
-
RENEWAL_ORDER = "rn"
-
AFFILIATE = "af"
-
DEFAULT_AFFILIATE_ID = 1
-
-
CART_KEY = :cart_102019
-
CART_GUID_KEY = :cart_guid_102019
-
AID = :aid_102019
-
AID_LI = :aid_li_102019
-
end
-
require 'digest/md5'
-
require 'zip/zip'
-
require 'openssl'
-
#require 'zip/zipfilesystem'
-
-
class SignedCertificate < ActiveRecord::Base
-
include CertificateType
-
include CertificateProperties
-
# using_access_control
-
serialize :organization_unit
-
serialize :subject_alternative_names
-
belongs_to :parent, :foreign_key=>:parent_id,
-
:class_name=> 'SignedCertificate', :dependent=>:destroy
-
belongs_to :csr, touch: true
-
delegate :certificate_content, to: :csr
-
delegate :certificate_order, to: :certificate_content
-
belongs_to :certificate_lookup
-
validates_presence_of :body, :if=> Proc.new{|r| !r.parent_cert}
-
validates :csr_id, :presence=>true, :on=>:save
-
validate :proper_certificate?, :if=>
-
Proc.new{|r| !r.parent_cert && !r.body.blank?}
-
has_many :sslcom_ca_revocation_requests, as: :api_requestable
-
has_many :sslcom_ca_requests, as: :api_requestable
-
#validate :same_as_previously_signed_certificate?, :if=> '!csr.blank?'
-
belongs_to :registered_agent
-
has_one :revocation, :class_name => "Revocation", :foreign_key => "revoked_signed_certificate_id"
-
has_one :replacement, through: :revocation, class_name: "SignedCertificate",
-
source: "replacement_signed_certificate", foreign_key: "replacement_signed_certificate_id"
-
-
-
attr :parsed
-
attr_accessor :email_customer
-
-
BEGIN_TAG="-----BEGIN CERTIFICATE-----"
-
END_TAG="-----END CERTIFICATE-----"
-
BEGIN_PKCS7_TAG="-----BEGIN PKCS7-----"
-
END_PKCS7_TAG="-----END PKCS7-----"
-
-
IIS_INSTALL_LINK = "https://www.ssl.com/how-to/modern-iis-ssl-installation-the-easy-way/"
-
CPANEL_INSTALL_LINK = "https://www.ssl.com/how-to/install-certificate-whm-cpanel/"
-
NGINX_INSTALL_LINK = "http://nginx.org/en/docs/http/configuring_https_servers.html"
-
V8_NODEJS_INSTALL_LINK = "http://nodejs.org/api/https.html"
-
JAVA_INSTALL_LINK = "https://www.ssl.com/how-to/how-to-install-a-certificate-on-java-based-web-servers/"
-
OTHER_INSTALL_LINK = "https://www.ssl.com/article/intermediate-certificate-download/"
-
APACHE_INSTALL_LINK = "https://www.ssl.com/how-to/install-ssl-apache-mod-ssl/"
-
AMAZON_INSTALL_LINK = "http://aws.amazon.com/documentation/"
-
-
APACHE_BUNDLE = "ca-bundle-client.crt"
-
AMAZON_BUNDLE = "ca-chain-amazon.crt"
-
-
OID_DV = "2.23.140.1.2.1"
-
OID_OV = "2.23.140.1.2.2"
-
OID_IV = "2.23.140.1.2.3"
-
OID_EV = "2.23.140.1.1"
-
OID_EVCS = "2.23.140.1.3"
-
OID_CS = "2.23.140.1.4.1"
-
OID_DOC_SIGNING = "1.3.6.1.4.1.311.10.3.12"
-
OID_TEST = "2.23.140.2.1"
-
-
after_initialize do
-
if new_record?
-
self.email_customer ||= ejbca_username.blank? ? false : true
-
end
-
end
-
-
before_create do |s|
-
s.decoded=s.decode
-
s.serial=s.decoded ? s.decoded_serial : ""
-
s.status ||= "issued"
-
end
-
-
after_create do |s|
-
s.csr.certificate_content.issue! unless %w(ShadowSignedCertificate ManagedCertificate).include?(self.type)
-
end
-
-
after_save do |s|
-
unless %w(ShadowSignedCertificate ManagedCertificate).include?(self.type)
-
s.send_processed_certificate
-
cc=s.csr.certificate_content
-
if cc.preferred_reprocessing?
-
cc.preferred_reprocessing=false
-
cc.save
-
end
-
co=cc.certificate_order
-
unless co.site_seal.fully_activated?
-
co.site_seal.assign_attributes({workflow_state: "fully_activated"}, without_protection: true)
-
co.site_seal.save
-
end
-
co.validation.approve! unless(co.validation.approved? || co.validation.approved_through_override?)
-
last_sent=s.csr.domain_control_validations.last_sent
-
last_sent.satisfy! if(last_sent && !last_sent.satisfied?)
-
unless cc.url_callbacks.blank?
-
cert = ApiCertificateRetrieve.new(query_type: "all_certificates")
-
co.to_api_retrieve cert, format: "nginx"
-
co_json = Rabl::Renderer.json(cert,File.join("api","v1","api_certificate_requests", "show_v1_4"),
-
view_path: 'app/views', locals: {result:cert})
-
cc.callback(co_json)
-
end
-
end
-
end
-
-
scope :live, -> {where{type == nil}}
-
-
scope :most_recent_expiring, lambda{|start, finish|
-
find_by_sql("select * from signed_certificates as T where expiration_date between '#{start}' AND '#{finish}' AND created_at = ( select max(created_at) from signed_certificates where common_name like T.common_name )")}
-
-
scope :by_public_key, lambda { |pubKey|
-
where{replace(replace(decoded, ' ', ''), '\r\n', '\n') =~ '%' + pubKey + '%'}
-
}
-
-
scope :search, lambda { |term|
-
where("MATCH (common_name, url, body, decoded, ext_customer_ref, ejbca_username) AGAINST ('#{term}')")
-
}
-
-
scope :search_with_terms, lambda { |term|
-
term ||= ""
-
term = term.strip.split(/\s(?=(?:[^']|'[^']*')*$)/)
-
filters = { common_name: nil, sans: nil, effective_date: nil, expiration_date: nil, status: nil }
-
-
filters.each {|fn, fv|
-
term.delete_if { |s| s =~ Regexp.new(fn.to_s+"\\:\\'?([^']*)\\'?"); filters[fn] ||= $1; $1 }
-
}
-
term = term.empty? ? nil : term.join(" ")
-
-
return nil if [term, *(filters.values)].compact.empty?
-
-
result = self.all
-
unless term.blank?
-
result = result.where {
-
(common_name =~ "%#{term}%") |
-
(subject_alternative_names =~ "%#{term}%") |
-
(status =~ "%#{term}%")}
-
end
-
-
%w(common_name).each do |field|
-
query = filters[field.to_sym]
-
result = result.where{ common_name =~ "%#{query}%" } if query
-
end
-
-
%w(sans).each do |field|
-
query = filters[field.to_sym]
-
result = result.where{ subject_alternative_names =~ "%#{query}%" } if query
-
end
-
-
%w(effective_date expiration_date).each do |field|
-
query = filters[field.to_sym]
-
if query
-
query = query.split("-")
-
start = Date.strptime query[0], "%m/%d/%Y"
-
finish = query[1] ? Date.strptime(query[1], "%m/%d/%Y") : start + 1.day
-
-
if field == "effective_date"
-
result = result.where{ (effective_date >> (start..finish)) }
-
elsif field == "expiration_date"
-
result = result.where{ (expiration_date >> (start..finish)) }
-
end
-
end
-
end
-
-
%w(status).each do |field|
-
query = filters[field.to_sym]
-
result = result.where{ status =~ "%#{query}%" } if query
-
end
-
-
result.uniq
-
}
-
-
def self.renew(start, finish)
-
cl = CertificateLookup.includes{signed_certificates}.
-
most_recent_expiring(start,finish).map(&:signed_certificates).flatten.compact
-
# just update expiration date for rebilling, but do not save it to SignedCertificate
-
mre=self.most_recent_expiring(start,finish).each do |sc|
-
# replace signed_certificate with one from lookups
-
remove = cl.select{|c|c.common_name == sc.common_name}.
-
sort{|a,b|a.created_at.to_i <=> b.created_at.to_i}
-
if remove.last
-
sc = cl.delete(remove.last)
-
remove.each {|r| cl.delete(r)}
-
end
-
end
-
tmp_certs={}
-
result = []
-
cl.each do |sc|
-
if tmp_certs[sc.common_name]
-
tmp_certs[sc.common_name] << sc
-
else
-
tmp_certs.merge! sc.common_name => [sc]
-
end
-
end
-
tmp_certs
-
tmp_certs.each do |k,v|
-
result << tmp_certs[k].max{|a,b|a.created_at.to_i <=> b.created_at.to_i}
-
end
-
expiring = (mre << result).flatten
-
#expiring.each {|e|e.certificate_order.do_auto_renew}
-
end
-
-
def public_key
-
openssl_x509.public_key
-
end
-
-
def public_key_sha1
-
OpenSSL::Digest::SHA1.new(public_key.to_der).to_s
-
end
-
-
def common_name_to_unicode
-
SimpleIDN.to_unicode read_attribute(:common_name)
-
end
-
-
def body=(certificate)
-
return if certificate.blank?
-
self[:body] = SignedCertificate.enclose_with_tags(certificate.strip)
-
unless Settings.csr_parser=="remote"
-
begin
-
parsed = if certificate=~ /PKCS7/
-
pkcs7=OpenSSL::PKCS7.new(self[:body])
-
self[:body]=pkcs7.to_s
-
pkcs7.certificates.first
-
else
-
OpenSSL::X509::Certificate.new(self[:body].strip)
-
end
-
rescue Exception => ex
-
logger.error ex
-
errors.add :base, 'error: could not parse certificate'
-
else
-
self[:parent_cert] = false
-
self[:common_name] = parsed.subject.common_name.force_encoding('UTF-8') if parsed.subject.common_name
-
self[:organization] = parsed.subject.organization.force_encoding('UTF-8') if parsed.subject.organization
-
self[:organization_unit] = ou_array(parsed.subject.to_s)
-
self[:state] = parsed.subject.region.force_encoding('UTF-8') if parsed.subject.region
-
self[:locality] = parsed.subject.locality.force_encoding('UTF-8') if parsed.subject.locality
-
pc=field_array("postalCode", parsed.subject.to_s)
-
self[:postal_code] = pc.first unless pc.blank?
-
self[:country] = parsed.subject.country.force_encoding('UTF-8') if parsed.subject.country
-
street=field_array("street", parsed.subject.to_s)
-
unless street.blank?
-
street.each_with_index do |s, i|
-
break if i>=2
-
self["address#{i+1}".to_sym] = field_array("street", parsed.subject.to_s)[0]
-
end
-
end
-
self[:signature] = parsed.subject_key_identifier.force_encoding('UTF-8') if parsed.subject_key_identifier
-
self[:fingerprint] = OpenSSL::Digest::SHA1.new(parsed.to_der).to_s
-
self[:fingerprintSHA] = "SHA1"
-
self[:effective_date] = parsed.not_before
-
self[:expiration_date] = parsed.not_after
-
self[:subject_alternative_names] = parsed.subject_alternative_names.map{|san| san.force_encoding('UTF-8')}
-
#TODO ecdsa throws exception. Find better method
-
self[:strength] = parsed.public_key.instance_of?(OpenSSL::PKey::EC) ?
-
(matched[1] if matched=parsed.to_text.match(/Private-Key\: \((\d+)/)) : parsed.strength
-
end
-
else
-
ssl_util = Savon::Client.new Settings.certificate_parser_wsdl
-
begin
-
response = ssl_util.parse_certificate do |soap|
-
soap.body = {:csr => certificate}
-
end
-
rescue Exception => ex
-
logger.error ex
-
else
-
self[:parent_cert] = false
-
@parsed = response.to_hash[:multi_ref]
-
unless @parsed.is_a? Array
-
return
-
end
-
certs = []
-
1.times do |i|
-
certs[i] = (i == 0) ? self : certs[i-1].create_parent(:parent_cert=>true)
-
certs[i][:common_name] = @parsed[i][:cn][:cn]
-
certs[i][:organization] = @parsed[i][:o][:o]
-
certs[i][:organization_unit] = @parsed[i][:ou][:ou]
-
certs[i][:address1] = @parsed[i][:street][:street]
-
certs[i][:state] = @parsed[i][:st][:st]
-
certs[i][:locality] = @parsed[i][:l][:l]
-
certs[i][:country] = @parsed[i][:c][:c]
-
certs[i][:signature] = @parsed[i][:signature]
-
certs[i][:fingerprint] = @parsed[i][:fingerprint]
-
certs[i][:fingerprintSHA] = @parsed[i][:fingerprint_sha]
-
certs[i][:effective_date] = @parsed[i][:eff_date]
-
certs[i][:expiration_date] = @parsed[i][:exp_date]
-
certs[i].save unless i==0
-
end
-
end
-
end
-
end
-
-
def ssl_account
-
csr.certificate_content.certificate_order.ssl_account
-
end
-
-
# find the ratio remaining on the cert ie (today-effective_date/expiration_date-effective_date)
-
def duration_remaining
-
remaining_days/total_days
-
end
-
-
def used_days(round=false)
-
sum = (Time.now - effective_date)
-
(round ? sum.round : sum)/1.day
-
end
-
-
def remaining_days(round=false)
-
days = total_days-used_days
-
(round ? days.round : days)
-
end
-
-
def total_days(round=false)
-
sum = (expiration_date - effective_date)
-
(round ? sum.round : sum)/1.day
-
end
-
-
def expired?
-
return false unless expiration_date
-
expiration_date < (Time.new)
-
end
-
-
def issuer
-
openssl_x509.issuer.to_s
-
end
-
-
def is_sslcom_ca?
-
ca_id != nil || ejbca_username != nil || issuer.include?("O=EJBCA Sample")
-
end
-
-
def x509_certificates
-
SslcomCaRequest.where(username: ejbca_username).first.try(:x509_certificates) ||
-
certificate_content.x509_certificates
-
end
-
-
def create_signed_cert_zip_bundle(options={})
-
options[:is_windows]=false unless Settings.allow_windows_cr #having issues with \r\n so stick with linux format
-
co=csr.certificate_content.certificate_order
-
path="/tmp/"+friendly_common_name+".zip#{Time.now.to_i.to_s(32)}"
-
::Zip::ZipFile.open(path, Zip::ZipFile::CREATE) do |zos|
-
if certificate_content.ca
-
x509_certificates.drop(1).each do |x509_cert|
-
zos.get_output_stream((x509_cert.subject.common_name || x509_cert.serial.to_s).
-
gsub(/[\s\.\*\(\)]/,"_").upcase+'.crt') {|f|
-
f.puts (options[:is_windows] ? x509_cert.to_s.gsub(/\n/, "\r\n") : x509_cert.to_s)
-
}
-
end
-
else
-
co.bundled_cert_names(components: true).each do |file_name|
-
file=File.new(co.bundled_cert_dir+file_name.strip, "r")
-
zos.get_output_stream(file_name.strip) {|f|
-
f.puts (options[:is_windows] ? file.readlines.join("").gsub(/\n/, "\r\n") : file.readlines)}
-
end
-
end
-
cert = options[:is_windows] ? body.gsub(/\n/, "\r\n") : body
-
zos.get_output_stream(nonidn_friendly_common_name+file_extension){|f| f.puts cert}
-
end
-
path
-
end
-
-
def zipped_whm_bundle(is_windows=false)
-
is_windows=false unless Settings.allow_windows_cr #having issues with \r\n so stick with linux format
-
path="/tmp/"+friendly_common_name+".zip#{Time.now.to_i.to_s(32)}"
-
::Zip::ZipFile.open(path, Zip::ZipFile::CREATE) do |zos|
-
file=File.new(ca_bundle(is_windows: is_windows), "r")
-
zos.get_output_stream(nonidn_friendly_common_name+".ca-bundle") {|f|f.puts (is_windows ?
-
file.readlines.join("").gsub(/\n/, "\r\n") : file.readlines)}
-
cert = is_windows ? body.gsub(/\n/, "\r\n") : body
-
zos.get_output_stream(nonidn_friendly_common_name+file_extension){|f| f.puts cert}
-
end
-
path
-
end
-
-
def zipped_apache_bundle(is_windows=false)
-
is_windows=false unless Settings.allow_windows_cr #having issues with \r\n so stick with linux format
-
path="/tmp/"+friendly_common_name+".zip#{Time.now.to_i.to_s(32)}"
-
::Zip::ZipFile.open(path, Zip::ZipFile::CREATE) do |zos|
-
file=File.new(ca_bundle(is_windows: is_windows, is_open_ssl: true), "r")
-
zos.get_output_stream(APACHE_BUNDLE) {|f|f.puts (is_windows ?
-
file.readlines.join("").gsub(/\n/, "\r\n") : file.readlines)}
-
cert = is_windows ? body.gsub(/\n/, "\r\n") : body
-
zos.get_output_stream(nonidn_friendly_common_name+file_extension){|f| f.puts cert}
-
end
-
path
-
end
-
-
def zipped_amazon_bundle(is_windows=false)
-
is_windows=false unless Settings.allow_windows_cr #having issues with \r\n so stick with linux format
-
co=csr.certificate_content.certificate_order
-
path="/tmp/"+friendly_common_name+".zip#{Time.now.to_i.to_s(32)}"
-
::Zip::ZipFile.open(path, Zip::ZipFile::CREATE) do |zos|
-
file=File.new(ca_bundle(is_windows: is_windows, server: "amazon"), "r")
-
zos.get_output_stream(AMAZON_BUNDLE) {|f|f.puts (is_windows ?
-
file.readlines.join("").gsub(/\n/, "\r\n") : file.readlines)}
-
cert = is_windows ? body.gsub(/\n/, "\r\n") : body
-
zos.get_output_stream(nonidn_friendly_common_name+file_extension){|f| f.puts cert}
-
end
-
path
-
end
-
-
def zipped_pkcs7(is_windows=false)
-
is_windows=false unless Settings.allow_windows_cr #having issues with \r\n so stick with linux format
-
co=csr.certificate_content.certificate_order
-
path="/tmp/"+friendly_common_name+".zip#{Time.now.to_i.to_s(32)}"
-
::Zip::ZipFile.open(path, Zip::ZipFile::CREATE) do |zos|
-
cert = is_windows ? body.gsub(/\n/, "\r\n") : body
-
zos.get_output_stream(nonidn_friendly_common_name+".p7b"){|f| f.puts to_pkcs7}
-
end
-
path
-
end
-
-
def send_processed_certificate(options=nil)
-
# for production certs, attached the bundle, change workflow and send site seal
-
unless certificate_order.certificate.is_code_signing?
-
zip_path =
-
if certificate_order.is_iis?
-
zipped_pkcs7
-
elsif certificate_order.is_nginx?
-
to_nginx_file
-
elsif certificate_order.is_cpanel?
-
zipped_whm_bundle
-
elsif certificate_order.is_apache?
-
zipped_apache_bundle
-
else
-
create_signed_cert_zip_bundle
-
end
-
certificate_order.site_seal.fully_activate! unless certificate_order.site_seal.fully_activated?
-
if email_customer
-
certificate_order.processed_recipients.map{|r|r.split(" ")}.flatten.uniq.each do |c|
-
begin
-
OrderNotifier.processed_certificate_order(contact: c,
-
certificate_order: certificate_order, file_path: zip_path).deliver
-
# OrderNotifier.processed_certificate_order(contact: Settings.shadow_certificate_recipient,
-
# certificate_order: certificate_order, file_path: zip_path).deliver if certificate_order.certificate_content.ca
-
OrderNotifier.site_seal_approve(c, certificate_order).deliver if certificate_order.certificate.is_server?
-
rescue Exception=>e
-
logger.error e.backtrace.inspect
-
end
-
end
-
end
-
end
-
# # for shadow certs, only send the certificate
-
# begin
-
# if certificate_content.ca and !certificate_content.ca.host.include?(SslcomCaApi::PRODUCTION_IP) # no shadow cert if this is production
-
# certificate_order.certificate.cas.shadow.to_a.uniq{|ca|[ca.profile_name,ca.end_entity]}.each do |shadow_ca|
-
# certificate_order.apply_for_certificate(mapping: shadow_ca)
-
# OrderNotifier.processed_certificate_order(contact: Settings.shadow_certificate_recipient,
-
# certificate_order: certificate_order,
-
# certificate_content: certificate_content,
-
# signed_certificate: certificate_order.shadow_certificates.last).deliver
-
# end
-
# end
-
# rescue Exception=>e
-
# logger.error e.message
-
# e.backtrace.each { |line| logger.error line }
-
# end
-
end
-
-
def friendly_common_name
-
(common_name || csr.common_name || serial).gsub('*', 'STAR').gsub('.', '_')
-
end
-
-
def nonidn_friendly_common_name
-
SimpleIDN.to_ascii(read_attribute(:common_name) || csr.common_name||
-
certificate_content.ref).gsub('*', 'STAR').gsub('.', '_')
-
end
-
-
def expiration_date_js
-
expiration_date.to_s
-
end
-
-
def created_at_js
-
created_at.to_s
-
end
-
-
def ou_array(subject)
-
s=subject_to_array(subject)
-
s.select do |o|
-
h=Hash[*o]
-
true unless (h["OU"]).blank?
-
end.map{|ou|ou[1]}
-
end
-
-
def field_array(field,subject)
-
s=subject_to_array(subject)
-
s.select do |o|
-
h=Hash[*o]
-
true unless (h[field]).blank?
-
end.map{|f|f[1]}
-
end
-
-
def public_cert(cn=nil,port=443)
-
cn=([self.common_name]+(self.subject_alternative_names||[])).find{|n|
-
CertificateContent.is_tld?(n)} unless cn
-
CertificateContent.find_or_create_installed(cn)
-
end
-
-
def is_intranet?
-
([self.common_name]+(self.subject_alternative_names||[])).uniq.all? {|n|CertificateContent.is_intranet?(n)}
-
end
-
-
def is_tld?
-
([self.common_name]+(self.subject_alternative_names||[])).uniq.any? {|n|CertificateContent.is_tld?(n)}
-
end
-
-
def ca_bundle(options={})
-
tmp_file="#{Rails.root}/tmp/sc_int_#{id}.txt"
-
File.open(tmp_file, 'wb') do |f|
-
tmp=""
-
if certificate_content.ca
-
x509_certificates.drop(1).each do |x509_cert|
-
tmp<<x509_cert.to_s
-
end
-
else
-
certificate_order.bundled_cert_names(options).each do |file_name|
-
file=File.new(certificate_order.bundled_cert_dir+file_name.strip, "r")
-
tmp << file.readlines.join("")
-
end
-
end
-
tmp.gsub!(/\n/, "\r\n") #if options[:is_windows]
-
f.write tmp
-
end
-
tmp_file
-
end
-
-
def revoked_by
-
SignedCertificate.where{serial =~ "%"}.last.system_audits.where{action=="revoked"}.last.owner.login
-
end
-
-
def self.print_revoked_by(serials)
-
serials.each do |serial_prefix|
-
sc=SignedCertificate.where{(serial =~ "#{serial_prefix}%") & (status=="revoked")}.last
-
audit=sc.system_audits.where{action=="revoked"}.last
-
p [sc.common_name,
-
serial_prefix,
-
audit.owner.login,
-
audit.created_at.strftime('%Y-%m-%d %H:%M:%S')]
-
end
-
end
-
-
def to_nginx(is_windows=nil, options={})
-
"".tap do |tmp|
-
if certificate_content.ca_id
-
x509_certs=if options[:order]=="reverse"
-
x509_certificates.reverse
-
elsif options[:order]=="rotate"
-
x509_certificates.rotate
-
else
-
x509_certificates
-
end
-
x509_certs.each do |x509_cert|
-
tmp<<x509_cert.to_s
-
end
-
else
-
tmp << body+"\n"
-
certificate_order.bundled_cert_names(is_open_ssl: true, ascending_root: true).each do |file_name|
-
file=File.new(certificate_order.bundled_cert_dir+file_name.strip, "r")
-
tmp << file.readlines.join("")
-
end
-
end
-
tmp.gsub!(/\n/, "\r\n") if is_windows
-
end
-
end
-
-
def to_nginx_file(is_windows=nil)
-
tmp_file="#{Rails.root}/tmp/sc_int_#{id}.txt"
-
File.open(tmp_file, 'wb') do |f|
-
f.write to_nginx(is_windows)
-
end
-
tmp_file
-
end
-
-
def pkcs7_file
-
sc_int="#{Rails.root}/tmp/sc_int_#{id}.cer"
-
File.open(sc_int, 'wb') do |f|
-
tmp=""
-
certificate_order.bundled_cert_names(server: "iis").each do |file_name|
-
file=File.new(certificate_order.bundled_cert_dir+file_name.strip, "r")
-
tmp << file.readlines.join("")
-
end
-
f.write tmp
-
end
-
sc_pem="#{Rails.root}/tmp/sc_pem_#{id}.cer"
-
File.open(sc_pem, 'wb') do |f|
-
f.write body+"\n"
-
end
-
sc_pkcs7="#{Rails.root}/tmp/sc_pkcs7_#{id}.cer"
-
::CertUtil.pem_to_pkcs7(sc_pem, sc_int, sc_pkcs7)
-
sc_pkcs7
-
end
-
-
def to_pem
-
return body unless file_type=="PKCS#7"
-
sc_pkcs7="#{Rails.root}/tmp/sc_pkcs7_#{id}.cer"
-
File.open(sc_pkcs7, 'wb') do |f|
-
f.write body+"\n"
-
end
-
sc_pem="#{Rails.root}/tmp/sc_pem_#{id}.cer"
-
::CertUtil.pkcs7_to_pem(sc_pem, sc_pkcs7)
-
sc_pem
-
end
-
-
def to_pkcs7
-
if certificate_content.ca
-
(SslcomCaRequest.where(username: ejbca_username).first.try(:pkcs7) || certificate_content.pkcs7).to_s
-
else
-
comodo_cert = ComodoApi.collect_ssl(certificate_order, {response_type: "pkcs7"}).certificate
-
if comodo_cert
-
(BEGIN_PKCS7_TAG+"\n"+comodo_cert+END_PKCS7_TAG).gsub(/\n/, "\r\n") #temporary fix
-
else
-
return body if body.starts_with?(BEGIN_PKCS7_TAG)
-
File.read(pkcs7_file) # TODO need to fix some bug. ending characters not matching comodo's certs
-
end
-
end
-
end
-
-
def to_format(options={})
-
if certificate_content.ca
-
if options[:response_type]=="individually"
-
to_nginx
-
elsif options[:response_type]=="pkcs7"
-
to_pkcs7
-
else
-
SignedCertificate.remove_begin_end_tags(to_pkcs7)
-
end
-
else
-
ComodoApi.collect_ssl(certificate_order, options).certificate
-
end
-
end
-
-
def file_extension
-
if file_type=="PKCS#7"
-
'.p7b'
-
elsif certificate_order.is_iis?
-
'.cer'
-
else
-
'.crt'
-
end
-
end
-
-
def file_type
-
body.starts_with?(BEGIN_PKCS7_TAG) ? 'PKCS#7' : 'X.509'
-
end
-
-
def decode
-
begin
-
if self.file_type=='PKCS#7'
-
sc_pem="#{Rails.root}/tmp/sc_pem_#{id}.cer"
-
File.open(sc_pem, 'wb') do |f|
-
f.write body+"\n"
-
end
-
CertUtil.decode_certificate sc_pem, "pkcs7"
-
else
-
openssl_x509.to_text
-
end
-
rescue Exception
-
end
-
end
-
-
def ca
-
read_attribute(:ca_id).blank? ? ("comodo" if comodo_ca_id) : Ca.find(read_attribute(:ca_id))
-
end
-
-
def is_SHA2?
-
decoded =~ /sha2/
-
end
-
-
def is_SHA1?
-
decoded =~ /sha1/
-
end
-
-
def signature_algorithm
-
matched=decoded.match(/Signature Algorithm: (.*?)\n/)
-
matched[1] if matched
-
end
-
-
def self.decode_all
-
self.find_each {|s|s.update_column :decoded, s.decode}
-
end
-
-
# get the serial through regular expression of the decoded cert
-
def decoded_serial
-
# m=decoded.match(/Serial Number:\n(.*?)\n/m)
-
m=decoded.match(/Serial Number:(.*?)Signature/m)
-
unless m.blank?
-
if ca=="comodo"
-
m[1].strip.remove(":")
-
# "00"+m[1].strip.remove(":") # need to clear this up with Comodo
-
else
-
m[1].strip
-
end
-
end
-
end
-
-
def revoked?
-
status == "revoked"
-
end
-
-
def revoke!(reason)
-
unless certificate_content.ca.blank?
-
response=SslcomCaApi.revoke_ssl(self,reason)
-
update_column(:status, "revoked") if response.is_a?(SslcomCaRevocationRequest) and response.response=="OK"
-
else
-
update_column(:status, "revoked") if ComodoApi.revoke_ssl(serial: self.serial, api_requestable: self, refund_reason: reason)
-
end
-
end
-
-
def ejbca_username
-
read_attribute(:ejbca_username) or (csr.blank? ? nil : csr.sslcom_ca_requests.first.try(:username))
-
end
-
-
def ejbca_certificate
-
host = "https://192.168.100.5:8443/v1/certificate/pkcs10"
-
options={username: "testdv1.ssl.com1551117126063"}
-
req, res = SslcomCaApi.call_ca(host, options, options.to_json)
-
end
-
-
def self.revoke_and_reissue(fingerprints)
-
SignedCertificate.live.includes(:csr).where{fingerprint >> fingerprints.map(&:downcase)}.
-
find_each{|sc|
-
# revoke and reissue sc
-
}
-
end
-
-
private
-
-
def proper_certificate?
-
if Settings.csr_parser=="remote"
-
errors[:base]<<'invalid certificate' unless @parsed.is_a?(Array)
-
end
-
end
-
-
def same_as_previously_signed_certificate?
-
if csr.signed_certificate && csr.signed_certificate.body == body
-
errors.add :base, "signed certificate is the same as previously saved one"
-
end
-
end
-
-
def subject_to_array(subject)
-
subject.split(/\/(?=[\w\d\.]+\=)/).reject{|o|o.blank?}.map{|o|o.split(/(?<!\\)=/)}
-
end
-
-
def self.remove_begin_end_tags(certificate)
-
certificate.gsub!(/-+BEGIN.+?(CERTIFICATE|PKCS7)-+/,"") if certificate =~ /-+BEGIN.+?(CERTIFICATE|PKCS7)-+/
-
certificate.gsub!(/-+END.+?(CERTIFICATE|PKCS7)-+/,"") if certificate =~ /-+END.+?(CERTIFICATE|PKCS7)-+/
-
certificate
-
end
-
-
# openssl is very finicky and requires opening and ending tags with exactly 5(-----) dashes on each side
-
def self.enclose_with_tags(cert)
-
if cert =~ /PKCS7/
-
# it's PKCS7
-
cert.gsub!(/-+BEGIN PKCS7-+/,"")
-
cert = BEGIN_TAG + "\n" + cert.strip
-
cert.gsub!(/-+END PKCS7-+/,"")
-
cert = cert + "\n" unless cert=~/\n\Z\z/
-
cert = cert + END_TAG + "\n"
-
else
-
unless cert =~ Regexp.new(BEGIN_TAG)
-
cert.gsub!(/-+BEGIN.+?CERTIFICATE-+/,"")
-
cert = BEGIN_TAG + "\n" + cert.strip
-
end
-
unless cert =~ Regexp.new(END_TAG)
-
cert.gsub!(/-+END.+?CERTIFICATE-+/,"")
-
cert = cert + "\n" unless cert=~/\n\Z\z/
-
cert = cert + END_TAG + "\n"
-
end
-
end
-
cert
-
end
-
-
# one time utility function to populate the fingerprint column
-
def self.populate_fingerprints_serials
-
self.find_each {|s|
-
unless s.body.blank?
-
s.update_columns(serial: s.decoded_serial,
-
fingerprint: OpenSSL::Digest::SHA1.new(s.openssl_x509.to_der).to_s, fingerprintSHA: "SHA1") if s.openssl_x509
-
end
-
}
-
end
-
end
-
-
require 'net/http'
-
require 'net/https'
-
require 'open-uri'
-
require 'timeout'
-
-
-
# A site check is a query from the website to
-
# query the ssl status of a domain
-
-
class SiteCheck < ActiveRecord::Base
-
belongs_to :certificate_lookup
-
-
attr_accessor :verify_trust, :ssl_client, :openssl_connect_result
-
-
validates :url, :presence=>true, :on=>:save
-
-
after_initialize do
-
self.lookup
-
self.verify_trust ||= true
-
end
-
-
before_create :create_certificate_lookup
-
-
COMMAND=->(url, port){%x"echo QUIT | openssl s_client -servername #{url} -connect #{url}:#{port} -CAfile /usr/lib/ssl/certs/ca-certificates.crt"}
-
TIMEOUT_DURATION=10
-
-
def openssl_connect(port=443)
-
self.openssl_connect_result=timeout(TIMEOUT_DURATION) do
-
COMMAND.call self.url, port
-
end
-
rescue
-
end
-
-
def s_client_issuers
-
self.openssl_connect_result ||= openssl_connect
-
self.openssl_connect_result.scan(/i\:(.+?)\n/).flatten
-
end
-
-
def lookup
-
context = OpenSSL::SSL::SSLContext.new
-
if self.verify_trust
-
#context.verify_depth=5
-
context.ca_file="/usr/lib/ssl/certs/ca-certificates.crt"
-
context.verify_mode = OpenSSL::SSL::VERIFY_NONE
-
end
-
Timeout.timeout(10) do
-
u,p = url.split ":"
-
tcp_client = TCPSocket.new(u, p || 443)
-
self.ssl_client = OpenSSL::SSL::SSLSocket.new tcp_client, context
-
self.ssl_client.connect
-
end
-
rescue
-
nil
-
end
-
-
def result
-
self.ssl_client.verify_result
-
end
-
-
def certificate
-
ssl_client.peer_cert_chain_with_openssl_extension.first unless all_certificates.blank?
-
end
-
-
def all_certificates
-
ssl_client.peer_cert_chain_with_openssl_extension unless ssl_client.blank?
-
end
-
-
def url=(o_url)
-
is_uri = o_url =~ /\:\/\//
-
write_attribute :url, is_uri ? URI.parse(o_url).host : o_url
-
end
-
-
def ou_array(subject)
-
s=subject_to_array(subject)
-
s.select do |o|
-
h=Hash[*o]
-
true unless (h["OU"]).blank?
-
end.map{|ou|ou[1]}
-
end
-
-
def subject_to_array(subject)
-
subject.split(/\/(?=[\w\d\.]+\=)/).reject{|o|o.blank?}.map{|o|o.split(/(?<!\\)=/)}
-
end
-
-
def create_certificate_lookup
-
self.certificate_lookup=
-
unless self.certificate.blank?
-
serial=self.certificate.serial.to_s
-
CertificateLookup.find_or_create_by_serial(serial,
-
serial: serial, certificate: self.certificate.to_s,
-
common_name: self.certificate.subject.common_name,
-
expires_at: self.certificate.not_after)
-
end
-
end
-
-
def self.days_left(subject,carry_over=false)
-
return 0 if subject.blank?
-
old_certificate=SiteCheck.new(url: subject, verify_trust: false).certificate
-
result=
-
if old_certificate && ((old_certificate.not_after.to_date - DateTime.now.to_date).to_i > 0)
-
(old_certificate.not_after.to_date - DateTime.now.to_date).to_i
-
else
-
0
-
end
-
carry_over && result > 90 ? 90 : result
-
end
-
end
-
class SiteSeal < ActiveRecord::Base
-
#using_access_control
-
has_many :certificate_orders, -> { unscope(where: [:workflow_state, :is_expired]) }
-
has_many :validations, through: :certificate_orders
-
has_many :validation_histories, through: :validations
-
attr_protected :workflow_state
-
-
EV_SEAL = 'ev'
-
OV_SEAL = 'ov'
-
DV_SEAL = 'dv'
-
-
FREE_SEAL_IMAGE = 'free_ssl_trust_logo.gif'
-
SEAL_IMAGE = 'ssl_trust_logo.gif'
-
-
REPORT_CACHE_KEY = "ssl_com_report_2015_"
-
-
REPORT_DIMENSIONS = 'height=500, width=400, top=100, left=100'
-
REPORT_ARTIFACTS_DIMENSIONS = 'height=600, width=400, top=100, left=100'
-
-
FULLY_ACTIVATED = :fully_activated
-
CONDITIONALLY_ACTIVATED = :conditionally_activated
-
DEACTIVATED = :deactivated
-
CANCELED = :canceled
-
-
ACTIVATE = "activate"
-
-
NEW_STATUS =
-
"site seal has not been activated yet"
-
FULLY_ACTIVATED_STATUS =
-
"site seal has been fully activated with all features"
-
CONDITIONALLY_ACTIVATED_STATUS =
-
"site seal has been partially activated, pending final approval"
-
DEACTIVATED_STATUS =
-
"site seal has been temporarily deactivated"
-
CANCELED_STATUS =
-
"site seal has been disabled pending investigation"
-
-
CLICK_TO_EXPAND = 'click to for more details'
-
-
before_create {|ss|
-
ss.ref=SecureRandom.hex(4)+'-'+Time.now.to_i.to_s(16)
-
}
-
-
preference :seal_image, :string
-
preference :artifacts_status, :string, :default=>ACTIVATE
-
-
include Workflow
-
workflow do
-
state :new do
-
event :fully_activate, :transitions_to => FULLY_ACTIVATED
-
event :conditionally_activate, :transitions_to => CONDITIONALLY_ACTIVATED
-
event :deactivate, :transitions_to => DEACTIVATED
-
event :report_abuse, :transitions_to => CANCELED
-
-
on_exit do
-
update_seal_type
-
end
-
end
-
-
state FULLY_ACTIVATED do
-
event :conditionally_activate, :transitions_to => CONDITIONALLY_ACTIVATED
-
event :deactivate, :transitions_to => DEACTIVATED
-
event :report_abuse, :transitions_to => CANCELED
-
end
-
-
state CONDITIONALLY_ACTIVATED do
-
event :fully_activate, :transitions_to => FULLY_ACTIVATED
-
event :deactivate, :transitions_to => DEACTIVATED
-
event :report_abuse, :transitions_to => CANCELED
-
end
-
-
state DEACTIVATED do
-
event :fully_activate, :transitions_to => FULLY_ACTIVATED
-
event :conditionally_activate, :transitions_to => CONDITIONALLY_ACTIVATED
-
event :report_abuse, :transitions_to => CANCELED
-
end
-
-
state CANCELED do
-
event :fully_activate, :transitions_to => FULLY_ACTIVATED
-
event :conditionally_activate, :transitions_to => CONDITIONALLY_ACTIVATED
-
event :deactivate, :transitions_to => DEACTIVATED
-
end
-
end
-
-
def update_seal_type
-
if certificate_order.migrated_from_v2?
-
if certificate_order.preferred_v2_product_description.downcase =~/trial/
-
self.update_attributes :seal_type=>DV_SEAL, :preferred_seal_image=>
-
FREE_SEAL_IMAGE
-
else
-
self.update_attributes :seal_type=>OV_SEAL, :preferred_seal_image=>
-
SEAL_IMAGE
-
end
-
else
-
self.update_attributes SiteSeal.generate_options(certificate_order.
-
certificate.product)
-
end
-
Rails.cache.delete REPORT_CACHE_KEY+self.id.to_s
-
end
-
-
def to_param
-
ref
-
end
-
-
def self.activate_all
-
SiteSeal.where{workflow_state == 'new'}.each do |ss|
-
ss.assign_attributes({workflow_state: "fully_activated"}, without_protection: true) if (ss.certificate_orders.first && (ss.certificate_orders.first.validation.approved? || ss.certificate_orders.first.validation.approved_through_override?))
-
ss.save
-
end
-
end
-
-
def self.generate_options(product)
-
case product
-
when /ev/
-
{:seal_type=>EV_SEAL, :preferred_seal_image=>SEAL_IMAGE}
-
when /high_assurance/, /ucc/, /wildcard/, /premiumssl/, /basicssl/
-
{:seal_type=>OV_SEAL, :preferred_seal_image=>SEAL_IMAGE}
-
when /free/
-
{:seal_type=>DV_SEAL, :preferred_seal_image=>FREE_SEAL_IMAGE}
-
end
-
end
-
-
def certificate_order
-
certificate_orders.last
-
end
-
-
def has_artifacts?
-
!certificate_order.validation_histories.
-
select(&:can_publish_to_site_seal?).empty? &&
-
preferred_artifacts_status == ACTIVATE
-
end
-
-
def status
-
-
end
-
-
def is_disabled?
-
canceled? || deactivated? || new?
-
end
-
-
def all_certificate_orders # includes renewals
-
CertificateOrder.unscoped.find(Rails.cache.fetch("#{cache_key}/all_certificate_orders") do
-
certs=[certificate_orders.last]
-
find_renewal = ->(co){ CertificateOrder.unscoped{co.renewal} if co }
-
renewal = find_renewal.call(certificate_order)
-
loop do
-
if renewal
-
certs<<renewal
-
renewal = find_renewal.call(renewal)
-
else
-
break
-
end
-
end
-
certs.map(&:id)
-
end)
-
end
-
-
def latest_certificate_order
-
all_certificate_orders.last
-
-
# if want to search by domain, but may cause confusion
-
# cn=certificate_order.common_name
-
# certificate_order.ssl_account.cached_certificate_orders.search_with_csr(cn).last
-
end
-
end
-
class SmimeClientEnrollmentOrder < Order
-
-
end
-
1
class SslAccount < ActiveRecord::Base
-
1
extend Memoist
-
1
using_access_control
-
1
acts_as_billable
-
1
easy_roles :roles
-
1
has_many :api_credentials
-
1
has_one :duo_account
-
1
has_many :billing_profiles
-
1
has_many :certificate_orders, -> { unscope(where: [:workflow_state, :is_expired]).includes([:orders]) },
-
before_add: Proc.new { |p, d|
-
folder=Folder.find_by(default: true, ssl_account_id: p.id)
-
d.folder_id= folder.id unless folder.blank?
-
} do
-
1
def current
-
where{workflow_state >>['new']}.first
-
end
-
-
1
def expired
-
joins(:signed_certificates).group("certificate_orders.id").having("max(signed_certificates.expiration_date) < ?", Date.today)
-
end
-
-
1
def revoked
-
joins{signed_certificates}.where{signed_certificates.status=="revoked"}
-
end
-
-
1
def unused
-
joins(:certificate_contents).where{certificate_contents.workflow_state == 'new'}
-
end
-
end
-
1
has_many :validations, through: :certificate_orders
-
1
has_many :site_seals, through: :certificate_orders
-
1
has_many :certificate_contents, through: :certificate_orders
-
1
has_many :domains, :dependent => :destroy
-
1
has_many :csrs, through: :certificate_contents
-
1
has_many :managed_csrs
-
1
has_many :signed_certificates, through: :certificate_contents do
-
1
def expired
-
where{expiration_date < Date.today}
-
end
-
-
1
def revoked
-
where{status=="revoked"}
-
end
-
end
-
1
has_many :certificate_contacts, through: :certificate_contents
-
1
has_many :registrants, through: :certificate_contents
-
1
has_one :epki_registrant, -> { where(status: Contact::statuses[:epki_agreement]) },
-
as: :contactable, class_name: 'Registrant', dependent: :destroy
-
1
has_one :reseller, :dependent => :destroy
-
1
has_one :affiliate, :dependent => :destroy
-
1
has_one :funded_account, :dependent => :destroy
-
1
has_many :orders, :as=>:billable, :after_add=>:build_line_items
-
1
has_many :monthly_invoices, as: :billable
-
1
has_many :daily_invoices, as: :billable
-
1
has_many :invoices, as: :billable
-
1
has_many :transactions, through: :orders
-
1
has_many :user_groups
-
1
has_many :api_certificate_requests, as: :api_requestable, dependent: :destroy
-
1
has_many :api_certificate_create_v1_4s, as: :api_requestable, class_name: "ApiCertificateCreate_v1_4"
-
1
has_many :api_certificate_retrieves, as: :api_requestable, class_name: "ApiCertificateRetrieve"
-
1
has_many :account_roles, class_name: "Role" # customizable roles that belong to this account
-
1
has_many :ssl_account_users, dependent: :destroy
-
100
has_many :users, -> { unscope(where: [:status]) }, through: :ssl_account_users
-
1
has_many :unscoped_users, through: :ssl_account_users
-
1
has_many :assignments
-
1
has_many :discounts, as: :benefactor, dependent: :destroy
-
1
has_many :saved_contacts, as: :contactable, class_name: 'CertificateContact', dependent: :destroy
-
1
has_many :saved_registrants, as: :contactable, class_name: 'Registrant', dependent: :destroy
-
1
has_many :all_saved_contacts, as: :contactable, class_name: 'Contact', dependent: :destroy
-
1
has_many :individual_validations, as: :contactable, class_name: 'IndividualValidation', dependent: :destroy
-
1
has_many :cdns
-
1
has_many :tags
-
1
has_many :folders, dependent: :destroy
-
1
has_many :notification_groups
-
1
has_many :scan_logs, through: :notification_groups
-
1
has_many :certificate_names, through: :certificate_contents
-
1
has_many :domain_control_validations, through: :certificate_names do
-
1
def sslcom
-
where.not certificate_contents: {ca_id: nil}
-
end
-
end
-
1
has_many :registered_agents
-
1
has_many :cas_certificates
-
1
has_many :cas, through: :cas_certificates
-
1
has_many :certificate_order_tokens
-
1
has_many :certificate_enrollment_requests
-
-
1
accepts_nested_attributes_for :reseller, :allow_destroy=>false
-
-
1
unless MIGRATING_FROM_LEGACY
-
#has_many :orders, :as=>:billable, :after_add=>:build_line_items
-
1
attr_readonly :acct_number
-
end
-
-
1
preference :reminder_status, :default=>true
-
1
preference :reminder_notice_triggers, :string
-
1
preference :reminder_include_reseller, :default=>true
-
1
preference :reminder_notice_destinations, :string, :default=>"0"
-
1
preference :reminder_include_cert_admin, :default=>true
-
1
preference :reminder_include_cert_tech, :default=>true
-
1
preference :processed_include_reseller, :default=>true
-
1
preference :processed_certificate_recipients, :string, :default=>"0"
-
1
preference :processed_include_cert_admin, :string, :default=>true
-
1
preference :processed_include_cert_tech, :string, :default=>true
-
1
preference :processed_include_reseller, :default=>true
-
1
preference :receipt_include_reseller, :default=>true
-
1
preference :receipt_recipients, :string, :default=>"0"
-
1
preference :receipt_include_cert_admin, :string, :default=>true
-
1
preference :receipt_include_cert_bill, :string, :default=>true
-
1
preference :confirmation_include_reseller, :default=>true
-
1
preference :confirmation_recipients, :string, :default=>"0"
-
1
preference :confirmation_include_cert_admin, :string, :default=>true
-
1
preference :confirmation_include_cert_bill, :string, :default=>true
-
1
preference :po_capable, default: false
-
-
1
before_validation :b_create, on: :create
-
1
after_create :initial_setup
-
100
after_save { users.find_each(&:touch) }
-
-
1
BILLING_METHODS = ['monthly', 'due_at_checkout', 'daily']
-
1
PULL_RESELLER = "pull_from_reseller"
-
1
PULL_ADMIN_TECH = "pull_from_admin_and_tech"
-
1
PULL_ADMIN = "pull_from_admin"
-
HUMAN_ATTRIBUTES = {
-
1
:preferred_processed_certificate_recipients=>"Certificate recipients",
-
:preferred_reminder_notice_destinations=>"Reminder recipients",
-
:preferred_receipt_recipients=>"Receipt recipients",
-
:preferred_confirmation_recipients=>"Confirmation recipients"
-
}
-
1
SETTINGS_SECTIONS = %w(processed_certificate receipt confirmation)
-
1
NUMBER_OF_TRIGGERS = 5
-
1
TRIGGER_RANGE = -364..364
-
463
@@reserved_routes ||= Rails.application.routes.named_routes.map{|r| r.to_s}
-
1
SHOW_TEAMS_THRESHOLD=0
-
1
SETTINGS_SECTIONS.each do |item|
-
3
validate "#{item}_recipients_format".to_sym,
-
:unless=>"preferred_#{item}_recipients=='0'"
-
end
-
1
validate :reminder_notice_destinations_format,
-
:unless=>"preferred_reminder_notice_destinations=='0'"
-
1
validate :preferred_reminder_notice_triggers_format
-
1
validates :acct_number, presence: true, uniqueness: true, on: :create
-
1
validates :ssl_slug, uniqueness: {case_sensitive: false}, length: {in: 2..20}, allow_nil: true
-
1
validates :company_name, length: {in: 2..20}, allow_nil: true
-
-
# default_scope ->{order("ssl_accounts.created_at desc")}
-
1925
default_scope{where{workflow_state << ['archived']}.order("ssl_accounts.created_at desc")}
-
-
1
scope :search_team, -> (term){
-
sql=%(MATCH (ssl_accounts.acct_number, ssl_accounts.company_name, ssl_accounts.ssl_slug) AGAINST ('#{term}') OR
-
MATCH (users.login, users.email) AGAINST ('#{term}')).squish
-
joins{users.outer}.where(sql)
-
}
-
-
1
include Workflow
-
1
workflow do
-
1
state :active do
-
1
event :archive, :transitions_to => :archived
-
end
-
-
1
state :archived do
-
1
event :retrieve, :transitions_to => :active
-
end
-
end
-
-
#before create function
-
1
def b_create
-
107
self.acct_number='a'+SecureRandom.hex(1)+
-
'-'+Time.now.to_i.to_s(32)
-
end
-
-
# before filter
-
1
def initial_setup
-
99
self.preferred_reminder_notice_triggers = "60", ReminderTrigger.find(1)
-
99
self.preferred_reminder_notice_triggers = "30", ReminderTrigger.find(2)
-
99
self.preferred_reminder_notice_triggers = "7", ReminderTrigger.find(3)
-
99
self.preferred_reminder_notice_triggers = "1", ReminderTrigger.find(4)
-
99
self.preferred_reminder_notice_triggers = "-30", ReminderTrigger.find(5)
-
99
generate_funded_account
-
99
create_api_credential if api_credential.blank?
-
99
create_folders
-
end
-
-
1
def api_credential
-
99
api_credentials.last
-
end
-
1
memoize :api_credential
-
-
1
def create_api_credential
-
99
@ac = ApiCredential.new
-
99
@ac.ssl_account_id = self.id
-
99
@ac.roles = "[#{Role.get_account_admin_id}]"
-
99
@ac.save
-
end
-
-
1
def self.human_attribute_name(attr, options={})
-
8
HUMAN_ATTRIBUTES[attr.to_sym] || super
-
end
-
-
1
def generate_funded_account
-
99
self.funded_account = FundedAccount.new(:cents=>0)
-
end
-
-
1
def total_amount_paid
-
Money.new(orders.not_test.inject(0) do
-
|sum, o| sum+=o.cents end)
-
end
-
-
1
def total_certs_bought
-
certificate_orders.not_new.count
-
end
-
-
1
def self.top_paid(include=[:users, :orders])
-
includes(include).sort {|a,b|
-
a.total_amount_paid <=> b.total_amount_paid}
-
end
-
-
1
def self.top_paid_users(how_many=10)
-
top_paid.last(how_many).map{|s|s.primary_user}
-
-
end
-
-
1
def self.top_paid_amounts(how_many=10)
-
top_paid([:orders]).last(how_many).map(&:total_amount_paid).map(&:format)
-
end
-
-
1
def reseller_tier_label
-
reseller.reseller_tier.label if (reseller && reseller.reseller_tier)
-
end
-
-
# def signed_certificates
-
# certificate_orders.map(&:certificate_contents).flatten.compact.
-
# map(&:csr).flatten.compact.map(&:signed_certificate)
-
# end
-
-
1
def unique_first_signed_certificates
-
([]).tap do |result|
-
tmp_certs={}
-
signed_certificates.compact.each do |sc|
-
if tmp_certs[sc.common_name]
-
tmp_certs[sc.common_name] << sc
-
else
-
tmp_certs.merge! sc.common_name => [sc]
-
end
-
end
-
tmp_certs
-
tmp_certs.each do |k,v|
-
result << tmp_certs[k].min{|a,b|a.created_at.to_i <=> b.created_at.to_i}
-
end
-
end
-
end
-
-
# does this domain satisfy pending validations of other domains on this team? Return list of satisfied names
-
# domain - the domain that has satisfied DV
-
1
def satisfy_related_dcvs(domain)
-
# the satisfied domain control validation method
-
dcv = domain.domain_control_validations.last
-
[].tap do |satisfied_names|
-
# TODO find only unvalidated domains or validated domains with older/different timestamp
-
all_certificate_names(domain.name,"unvalidated").includes(:domain_control_validations).each do |certificate_name|
-
if certificate_name.name!=domain.name and
-
DomainControlValidation.domain_in_subdomains?(domain.name,certificate_name.name) and
-
# team validated domain
-
(domain.certificate_content_id==nil or
-
# do they have the same public key
-
(domain.csr and certificate_name.csr and
-
domain.cached_csr_public_key_sha1==certificate_name.cached_csr_public_key_sha1))
-
certificate_name.domain_control_validations.create(dcv.attributes.except("id"))
-
# TODO only call apply_for_certificate once
-
satisfied_names << certificate_name.name
-
end
-
end
-
end
-
end
-
-
# does already validated domain validate `certificate_name`? If so, create a dcv with satisfied status
-
# certificate_name - the domain we are looking up
-
1
def other_dcvs_satisfy_domain(certificate_names)
-
certificate_names = [certificate_names] if certificate_names.is_a?(CertificateName)
-
# TODO find only validated domains
-
satisfied = []
-
all_certificate_names(certificate_names.map(&:name),"validated").
-
includes(:validated_domain_control_validations).each do |cn|
-
certificate_names.each do |certificate_name|
-
if cn.id!=certificate_name.id and DomainControlValidation.domain_in_subdomains?(cn.name,certificate_name.name)
-
dcv = cn.validated_domain_control_validations.last # TODO find dcv.satisfied?
-
if dcv && dcv.identifier_found
-
# email validation
-
if dcv.dcv_method =~ /email/ or
-
# http/s or cname must have the same public key
-
(Settings.compare_public_key ? (cn.csr and certificate_name.csr and
-
cn.cached_csr_public_key_sha1==certificate_name.cached_csr_public_key_sha1) : true)
-
satisfied << certificate_name.domain_control_validations.create(dcv.attributes.except("id"))
-
break
-
end
-
end
-
end
-
end
-
end
-
satisfied
-
end
-
-
1
def unique_signed_certificates
-
([]).tap do |result|
-
tmp_certs={}
-
signed_certificates.compact.each do |sc|
-
if tmp_certs[sc.common_name]
-
tmp_certs[sc.common_name] << sc
-
else
-
tmp_certs.merge! sc.common_name => [sc]
-
end
-
end
-
tmp_certs
-
tmp_certs.each do |k,v|
-
result << tmp_certs[k].max{|a,b|a.expiration_date.to_i <=> b.expiration_date.to_i}
-
end
-
end
-
end
-
-
1
def unrenewed_signed_certificates(renew_threshold=nil)
-
unique_signed_certificates.select{|sc|
-
sc.certificate_order.renewal.blank? || (renew_threshold ?
-
(sc.certificate_order.renewal.created_at < renew_threshold.days.ago) : false)}
-
end
-
-
1
def renewed_signed_certificates
-
unique_signed_certificates.select{|sc| sc.certificate_order.renewal}
-
end
-
-
1
def can_buy?(item)
-
item = Certificate.for_sale.find_by_product(item[ShoppingCart::PRODUCT_CODE]) if item.is_a?(Hash)
-
if item.blank?
-
return false
-
elsif item.reseller_tier.nil?
-
return true
-
elsif reseller.nil?
-
return false
-
end
-
true if item.reseller_tier == reseller.reseller_tier
-
end
-
-
1
def is_registered_reseller?
-
Rails.cache.fetch("#{cache_key}/is_registered_reseller") do
-
has_role?('reseller') && reseller.try("complete?")
-
end
-
end
-
-
1
def is_new_reseller?
-
Rails.cache.fetch("#{cache_key}/is_new_reseller") do
-
has_role?('new_reseller')
-
end
-
end
-
-
1
def clear_new_certificate_orders
-
certificate_orders.is_new.each(&:destroy)
-
end
-
-
1
def clear_new_product_orders
-
product_orders.is_new.each(&:destroy)
-
end
-
-
1
def has_only_credits?
-
(certificate_orders.credits.count > 0) && (certificate_orders.credits.count==certificate_orders.not_new.count)
-
end
-
-
1
def has_credits?
-
certificate_orders.unused_credits.count > 0
-
end
-
-
1
def has_certificate_orders?
-
certificate_orders.not_new.count > 0
-
end
-
-
# do any default certificates map to SSL.com chained Roots
-
1
def show_domains_manager?
-
Rails.cache.fetch("#{cache_key}/show_domains_manager") do
-
cas_certificates.default.any?{|cc|cc.certificate.is_server?}
-
end or
-
Rails.cache.fetch(CasCertificate::GENERAL_DEFAULT_CACHE) do
-
CasCertificate.general.default.any?{|cc|cc.certificate.is_server?}
-
end
-
end
-
-
1
%W(receipt confirmation).each do |et|
-
2
define_method("#{et}_recipients") do
-
[].tap do |addys|
-
addys << reseller.email if
-
is_registered_reseller? &&
-
send("preferred_#{et}_include_reseller?")
-
addys << send("preferred_#{et}_recipients") unless
-
send("preferred_#{et}_recipients")=="0"
-
addys.uniq!
-
addys << users.map(&:email); addys.flatten!; addys.uniq! if
-
addys.empty?
-
end
-
end
-
end
-
-
1
def set_reseller_default_prefs
-
self.preferred_reminder_include_cert_admin=false
-
self.preferred_reminder_include_cert_tech=false
-
self.preferred_processed_include_cert_admin=false
-
self.preferred_processed_include_cert_tech=false
-
self.preferred_receipt_include_cert_admin=false
-
self.preferred_receipt_include_cert_bill=false
-
self.preferred_confirmation_include_cert_admin=false
-
self.preferred_confirmation_include_cert_bill=false
-
self.save
-
end
-
-
1
def tier_suffix
-
(reseller && reseller.reseller_tier) ? ResellerTier.tier_suffix(reseller.reseller_tier.label) : ""
-
end
-
-
#def order_transactions
-
# oids=Order.select("orders.id").joins(:billable.type(SslAccount)).
-
# where(:billable_id=>id).map(&:id)
-
# OrderTransaction.where(:order_id + oids)
-
#end
-
#
-
#def successful_order_transactions
-
# order_transactions.where :success=>true
-
#end
-
-
# this upgrades or downgrades the account into a reseller tier
-
1
def adjust_reseller_tier(tier, reseller_fields=Reseller::TEMP_FIELDS)
-
#if account is not reseller, do it now else just change the tier number
-
if reseller.blank?
-
create_reseller(reseller_fields.reverse_merge(reseller_tier_id: ResellerTier.find_by_label(tier).id))
-
roles << "reseller"
-
set_reseller_default_prefs
-
users.each do |u|
-
u.set_roles_for_account(self, [Role.find_by_name(Role::RESELLER).id])
-
end
-
else
-
reseller.reseller_tier=ResellerTier.find_by_label(tier)
-
reseller.save
-
end
-
roles << "reseller" unless is_reseller?
-
roles.delete "new_reseller" if is_new_reseller?
-
save
-
reseller.completed! unless reseller.complete?
-
end
-
-
1
def api_certificate_requests_string
-
acr=api_certificate_requests.last
-
if acr
-
'curl -k -H "Accept: application/json" -H "Content-type: application/json" -X PUT -d '+
-
acr.raw_request.to_json + " " +acr.request_url
-
end
-
end
-
-
1
def adjust_funds(cents)
-
funded_account.update_attribute :cents, funded_account.cents+=cents
-
end
-
-
1
def self.api_credentials_for_all
-
self.find_each{|s|s.create_api_credential if s.api_credential.blank?}
-
end
-
-
1
def self.migrate_deposit(from_sa, to_sa, deposit, user)
-
to_sa.orders << deposit if deposit
-
if deposit && to_sa.orders.include?(deposit)
-
SystemAudit.create(
-
owner: user,
-
target: deposit,
-
notes: "Transfered deposit #{deposit.reference_number} from team acct ##{from_sa.acct_number} to team acct ##{to_sa.acct_number} on #{DateTime.now.strftime('%c')}.",
-
action: "Transfer Deposit To Team"
-
)
-
end
-
end
-
-
# from_sa - the ssl_account to migrate from
-
# to_sa - the ssl_account to migrate to
-
1
def self.migrate_orders(from_sa, to_sa, refs=[], user)
-
unless refs.blank?
-
orders_list = []
-
co_list = []
-
Order.where(reference_number: refs).each do |o|
-
to_sa.certificate_orders << o.cached_certificate_orders
-
o.cached_certificate_orders.each do |co|
-
co_orders = co.orders
-
to_sa.orders << co_orders
-
orders_list << co_orders
-
co_list << co
-
end
-
end
-
orders_list = orders_list.flatten.uniq.compact
-
co_list = co_list.flatten.uniq.compact
-
params = {
-
from_sa: from_sa,
-
to_sa: to_sa,
-
orders_list: orders_list,
-
co_list: co_list,
-
user: user
-
}
-
if orders_list.any?
-
OrderNotifier.order_transferred(params).deliver_now
-
migrate_orders_to_invoices(to_sa, orders_list)
-
migrate_orders_associations(params)
-
end
-
co_list.map(&:certificate_contacts).flatten.uniq.compact.each do |contact|
-
contact.update(parent_id: nil)
-
end
-
migrate_orders_system_audit(params)
-
end
-
end
-
-
1
def self.migrate_orders_associations(params)
-
list = []
-
# Funded Account Withdrawal used to pay for order
-
params[:orders_list].each do |o|
-
list << Order.where('description LIKE ?', "%#{Order::FAW}%")
-
.where('notes LIKE ?', "%#{o.reference_number}%").first
-
end
-
# Deposits used to pay for order
-
list << Order.where(id: params[:orders_list].map(&:deducted_from_id))
-
list = list.flatten.compact.uniq
-
params[:to_sa].orders << list if list.any?
-
end
-
-
1
def self.migrate_orders_system_audit(params)
-
notes_ext = "from team acct ##{params[:from_sa].acct_number} to team acct ##{params[:to_sa].acct_number} on #{DateTime.now.strftime('%c')}"
-
-
params[:co_list].each do |co|
-
SystemAudit.create(
-
owner: params[:user],
-
target: co,
-
notes: "Transfered certificate order #{co.ref} #{notes_ext}.",
-
action: "Transfer Certificate Order To Team"
-
)
-
end
-
params[:orders_list].each do |o|
-
SystemAudit.create(
-
owner: params[:user],
-
target: o,
-
notes: "Transfered order #{o.reference_number} #{notes_ext}.",
-
action: "Transfer Order To Team"
-
)
-
end
-
end
-
-
1
def self.migrate_orders_to_invoices(to_sa, orders_list=[])
-
invoiced_orders = orders_list.select {|io| io.state == 'invoiced'}
-
pending_invoice = nil
-
invoiced_orders.each do |o|
-
from_invoice = o.invoice
-
if from_invoice
-
exclude_params = %w{id reference_number created_at updated_at billable_id}
-
cur_params = from_invoice.attributes.except!(*exclude_params)
-
.merge(billable_id: to_sa.id)
-
target_invoice = if from_invoice.pending? && pending_invoice.nil?
-
pending_invoice = Invoice.get_or_create_for_team(to_sa)
-
else
-
Invoice.create(cur_params)
-
end
-
o.update(invoice_id: target_invoice.try(:id)) if target_invoice
-
end
-
from_invoice.destroy if from_invoice.orders.empty?
-
end
-
end
-
-
1
def primary_user
-
users.first
-
end
-
-
1
def self.ssl_slug_valid?(slug_str)
-
36
cur_ssl_slug = slug_str.strip.downcase
-
36
!cur_ssl_slug.blank? &&
-
SslAccount.find_by(ssl_slug: cur_ssl_slug).nil? &&
-
!@@reserved_routes.include?(cur_ssl_slug) &&
-
cur_ssl_slug.gsub(/([a-zA-Z]|_|-|\s|\d)/, '').length == 0
-
end
-
-
1
def get_invoice_label
-
return 'monthly' if billing_monthly?
-
return 'daily' if billing_daily?
-
''
-
end
-
-
1
def domain_names(only_ca = true)
-
cnames = self.certificate_names.order(created_at: :desc)
-
dnames = self.domains.order(created_at: :desc)
-
domain_names = []
-
cnames.each do |cn|
-
unless only_ca
-
domain_names << cn.name unless domain_names.include?(cn.name)
-
else
-
domain_names << cn.name unless domain_names.include?(cn.name) && cn.certificate_content.ca_id.nil?
-
end
-
end
-
dnames.each do |dn|
-
domain_names << dn.name unless domain_names.include?(dn.name)
-
end
-
domain_names
-
end
-
-
# concatenate team (Domain) and order scoped certificate_names
-
1
def all_certificate_names(roots=nil,cn_validated="",scope="sslcom")
-
roots=[roots] if roots.is_a?(String)
-
cn,dn= case cn_validated
-
when "validated"
-
[self.certificate_names.validated,self.domains.validated]
-
when "unvalidated"
-
[self.certificate_names.unvalidated,self.domains.unvalidated]
-
else
-
[self.certificate_names,self.domains]
-
end
-
cn=cn.sslcom if scope=="sslcom"
-
# query an array of domains
-
if roots
-
CertificateName.where(id: (Rails.cache.fetch(
-
"#{cache_key}/all_certificate_names/#{cn_validated+scope}/#{Digest::SHA1.hexdigest(roots.to_s)}") {
-
sql = []
-
roots.each do |root|
-
d=::PublicSuffix.parse(root)
-
sql << "name like '#{'%.'+d.domain}' OR name = '#{d.domain}'"
-
end
-
name_sql=->(scoped_names){scoped_names.where(sql.join(" OR "))}
-
(name_sql.call(cn)+name_sql.call(dn)).map(&:id).uniq
-
})).order(updated_at: :desc)
-
else # get all domains that belong to this account
-
CertificateName.where(id: (Rails.cache.fetch("#{cache_key}/all_certificate_names/#{cn_validated+scope}") {
-
(cn+dn).map(&:id).uniq
-
})).order(updated_at: :desc)
-
end
-
end
-
1
memoize :all_certificate_names
-
-
1
def all_csrs
-
Csr.where(id: (Rails.cache.fetch("#{cache_key}/all_csrs") {
-
if managed_csrs.empty?
-
csrs
-
elsif csrs.empty?
-
managed_csrs
-
else
-
(csrs + managed_csrs)
-
end.reject{|csr|csr.public_key_sha1.blank?}.uniq(&:public_key_sha1).map(&:id)
-
})).order(created_at: :desc)
-
end
-
-
1
def validated_domains
-
validated_domains = []
-
cnames = self.certificate_names
-
cnames.includes(:domain_control_validations).each do |cn|
-
dcv = cn.domain_control_validations.last
-
if dcv && dcv.identifier_found
-
validated_domains << cn.name unless validated_domains.include?(cn.name)
-
end
-
end
-
validated_domains
-
end
-
-
1
def is_validated?(domain)
-
validated_domains.include?(domain)
-
end
-
-
1
def get_invoice_pmt_description
-
billing_monthly? ? Order::MI_PAYMENT : Order::DI_PAYMENT
-
end
-
-
1
def get_account_admins
-
uid=Rails.cache.fetch("#{cache_key}/get_account_admins") do
-
users.with_role(Role::ACCOUNT_ADMIN).pluck(:id).uniq
-
end
-
uid ? User.find(uid) : nil
-
end
-
1
memoize :get_account_admins
-
-
1
def get_account_owner
-
uid=Rails.cache.fetch("#{cache_key}/get_account_owner") do
-
Assignment.where(
-
role_id: [Role.get_owner_id, Role.get_reseller_id], ssl_account_id: id
-
).pluck(:user_id).first
-
end
-
uid ? User.find(uid) : nil
-
end
-
1
memoize :get_account_owner
-
-
# def get_account_admins
-
# uid=Rails.cache.fetch("#{cache_key}/get_account_admins") do
-
# Assignment.where(
-
# role_id: [Role.get_account_admin_id], ssl_account_id: id
-
# ).pluck(:user_id)
-
# end
-
# uid ? User.find(uid) : nil
-
# end
-
# memoize :get_account_admins
-
#
-
1
def cached_users
-
User.where(id: (Rails.cache.fetch("#{cache_key}/cached_users") do
-
users.pluck(:id).uniq
-
end))
-
end
-
-
1
def cached_certificate_names
-
CertificateName.where(id: (Rails.cache.fetch("#{cache_key}/cached_certificate_names") do
-
certificate_names.pluck(:id).uniq
-
end))
-
end
-
-
1
def cached_orders
-
Order.where(id: (Rails.cache.fetch("#{cache_key}/cached_orders") do
-
orders.pluck(:id).uniq
-
end)).order(created_at: :desc)
-
end
-
1
memoize :cached_orders
-
-
1
def cached_certificate_orders
-
CertificateOrder.where(id: (Rails.cache.fetch("#{cache_key}/cached_certificate_orders") do
-
certificate_orders.pluck(:id).uniq
-
end)).order(created_at: :desc)
-
end
-
1
memoize :cached_certificate_orders
-
-
1
def cached_certificate_orders_count
-
Rails.cache.fetch("#{cache_key}/cached_certificate_orders_count") do
-
cached_certificate_orders.count
-
end
-
end
-
1
memoize :cached_certificate_orders_count
-
-
1
def cached_certificate_orders_pending
-
CertificateOrder.where(id: (Rails.cache.fetch("#{cache_key}/cached_certificate_orders_pending") do
-
certificate_orders.pending.pluck(:id)
-
end)).order(created_at: :desc)
-
end
-
1
memoize :cached_certificate_orders_pending
-
-
1
def cached_certificate_orders_incomplete
-
CertificateOrder.where(id: (Rails.cache.fetch("#{cache_key}/cached_certificate_orders_incomplete") do
-
certificate_orders.incomplete.pluck(:id)
-
end)).order(created_at: :desc)
-
end
-
1
memoize :cached_certificate_orders_incomplete
-
-
1
def cached_certificate_orders_credits
-
CertificateOrder.where(id: (Rails.cache.fetch("#{cache_key}/cached_certificate_orders_credits") do
-
certificate_orders.credits.pluck(:id)
-
end)).order(created_at: :desc)
-
end
-
1
memoize :cached_certificate_orders_credits
-
-
1
def cached_certificate_orders_credits_count
-
Rails.cache.fetch("#{cache_key}/cached_certificate_orders_credits_count") do
-
cached_certificate_orders_credits.count
-
end
-
end
-
1
memoize :cached_certificate_orders_credits_count
-
-
1
def cached_certificate_orders_pending_count
-
Rails.cache.fetch("#{cache_key}/cached_certificate_orders_pending_count") do
-
cached_certificate_orders_pending.count
-
end
-
end
-
1
memoize :cached_certificate_orders_pending_count
-
-
1
def cached_certificate_orders_incomplete_count
-
Rails.cache.fetch("#{cache_key}/cached_certificate_orders_incomplete_count") do
-
cached_certificate_orders_incomplete.count
-
end
-
end
-
1
memoize :cached_certificate_orders_incomplete_count
-
-
1
def get_team_name
-
2
company_name || acct_number
-
end
-
-
1
def to_slug
-
ssl_slug || acct_number
-
end
-
-
1
def expiring_certificates_for_old
-
results=[]
-
-
unique_first_signed_certificates.compact.each do |sc|
-
pd = (sc.expiration_date - sc.effective_date) / 1.day
-
ecd = sc.csr.certificate_content.duration
-
-
if pd && ecd
-
if (ecd - pd) > 825
-
results << Struct::Reminding.new(2, sc)
-
elsif (ecd - pd) > 365
-
results << Struct::Reminding.new(1, sc)
-
end
-
end
-
end
-
-
results
-
-
# unrenewed_signed_certificates.compact.each do |sc|
-
# scd = sc.created_at
-
# sed = sc.expiration_date
-
# unless sed.blank?
-
# if (((scd + 3.years) < sed) &&
-
# (Time.now < sed) &&
-
# (scd > 3.years.from_now) &&
-
# (scd < (Time.now - 2.years - 10.months)))
-
# results << Struct::Expiring.new(sc)
-
# end
-
# end
-
# end
-
end
-
-
1
def expiring_certificates
-
results=[]
-
-
if preferred_reminder_status
-
exp_dates=ReminderTrigger.all.map do|rt|
-
preferred_reminder_notice_triggers(rt).to_i
-
end.sort{|a,b|b<=>a} # order from highest to lowest value
-
-
unrenewed_signed_certificates.compact.each do |sc|
-
sed = sc.expiration_date
-
unless sed.blank?
-
exp_dates.each_with_index do |ed, i|
-
# determine if valid to send reminders and/or rebill at this point
-
if (i < exp_dates.count-1 && # be sure we don't over iterate
-
sed < ed.to_i.days.from_now && # is signed certificate expiration between exp intervals?
-
sed >= exp_dates[i+1].days.from_now)
-
results << Struct::Expiring.new(ed,exp_dates[i+1],sc) unless
-
renewed?(sc, exp_dates.first.to_i)
-
break
-
end
-
end
-
end
-
end
-
end
-
-
results
-
end
-
-
# years back - how many years back do we want to go on expired certificates
-
1
def expired_certificates(intervals, years_back=1)
-
year_in_days = 365
-
(Array.new(intervals.count){|i|i=[]}).tap do |results|
-
if preferred_reminder_status
-
unrenewed_signed_certificates.compact.each do |sc|
-
sed = sc.expiration_date
-
unless sed.blank?
-
years_back.times do |i|
-
years = year_in_days * (i+1)
-
adj_int = intervals.map{|i|i+years}
-
adj_int.each_with_index do |ed, i|
-
if i < adj_int.count-1 &&
-
sed < ed.to_i.days.ago &&
-
sed >= adj_int[i+1].days.ago
-
results[i] << Struct::Expiring.new(ed,adj_int[i+1],sc) unless
-
renewed?(sc, intervals.last)
-
break
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
-
#Reminder.preparing_recipients to locate point of injection for do-not-send list
-
1
def self.send_reminders
-
# ActiveRecord::Base.logger.level = Logger::INFO
-
logger.info "Sending SSL.com cert reminders. Type 'Q' and press Enter to exit this program"
-
SslAccount.unscoped.order('created_at').includes(
-
[:stored_preferences, {:certificate_orders =>
-
[:orders]}]).find_in_batches(batch_size: 250) do |s|
-
# find expired certs based on triggers.
-
logger.info "filtering out expired certs"
-
e_certs=s.map{|s|s.expiring_certificates}.reject{|e|e.empty?}.flatten
-
digest={}
-
self.send_and_create_reminders(e_certs, digest)
-
#find expired certs from n*1 years ago from ssl_accounts that do not have
-
#recent purchase history
-
remove = e_certs.map(&:cert).flatten.map(&:ssl_account).uniq
-
# should also filter out ssl_accounts who have recently logged in. We don't
-
# want to constantly email them even if they have expired certs from a several
-
# years ago
-
s = s - remove
-
digest.clear
-
intervals = [-30, -7, 16, 31] #0 represents this day, n * 1 years ago
-
e_certs = s.map{|s|s.expired_certificates(intervals)}.
-
transpose.map{|ec|ec.reject{|e|e==[]}.flatten}.flatten.compact
-
self.send_and_create_reminders(e_certs, digest, true, intervals)
-
end
-
logger.info "exiting ssl reminder app"
-
end
-
-
# def self.test
-
# SslAccount.unscoped.order('created_at').includes(
-
# [:stored_preferences, {:certificate_orders =>
-
# [:orders, :certificate_contents=>
-
# {:csr=>:signed_certificates}]}]).find_in_batches(batch_size: 250) do |batch_list|
-
# logger.info "Filtering out expiring certs"
-
# e_certs = batch_list.map{|batch| batch.expiring_certificates_for_old}.reject{|e|e.empty?}.flatten
-
# digest = {}
-
# SslAccount.send_notify(e_certs, digest)
-
# end
-
# end
-
-
1
def self.send_notify(expiring_certs, digest)
-
expiring_certs.each do |ec|
-
cert = ec.cert
-
contacts=[cert.csr.certificate_content.technical_contact,cert.csr.certificate_content.administrative_contact]
-
contacts.uniq.compact.each do |contact|
-
logger.info "adding contact to digest"
-
unless contact.email.blank? ||
-
SentReminder.exists?(trigger_value: ec.year,
-
expires_at: cert.expiration_date,
-
subject: cert.common_name,
-
recipients: contact.email)
-
dk = contact.to_digest_key
-
if digest[dk].blank?
-
digest.merge!({dk => [ec]})
-
else
-
digest[dk] << ec
-
end
-
end
-
end
-
end
-
unless digest.empty?
-
digest.each do |d|
-
u_certs = d[1].map(&:cert).map(&:common_name).uniq.compact
-
begin
-
unless u_certs.empty?
-
logger.info "Sending notification"
-
body = Reminder.digest_notify(d)
-
body.deliver unless body.to.empty?
-
end
-
d[1].each do |ec|
-
logger.info "create SentReminder"
-
SentReminder.find_or_initialize_by(trigger_value: ec.year,
-
expires_at: ec.cert.expiration_date,
-
signed_certificate_id: ec.cert.id,
-
subject: ec.cert.common_name,
-
body: body,
-
recipients: d[0].split(",").last).save
-
end
-
rescue Exception=>e
-
logger.error e.backtrace.inspect
-
raise e
-
end
-
end
-
end
-
end
-
-
1
def self.send_and_create_reminders(expired_certs, digest, past=false,
-
interval=nil)
-
expired_certs.each do |ec|
-
exempt_list = %w(
-
hepsi danskhosting webcruit
-
epsa\.com\.co
-
magicexterminating suburbanexterminating)
-
exempt_certs = ->(domain, exempt){exempt.find do |e|
-
domain=~eval("/#{e}/")
-
end}
-
if true #this should be a function testing for message digest
-
detect_abort
-
c = ec.cert
-
contacts=[c.csr.certificate_content.technical_contact,
-
c.csr.certificate_content.administrative_contact]
-
contacts.uniq.compact.each do |contact|
-
logger.info "adding contact to digest"
-
unless contact.email.blank? ||
-
SentReminder.exists?(trigger_value:
-
[ec.before, ec.after].join(", "),
-
expires_at: c.expiration_date, subject: c.common_name,
-
recipients: contact.email) ||
-
exempt_certs.(c.common_name, exempt_list)
-
dk=contact.to_digest_key
-
if digest[dk].blank?
-
digest.merge!({dk => [ec]})
-
else
-
digest[dk] << ec
-
end
-
end
-
end
-
else #currently doesn't get used
-
unless ec.cert.expiration_date.blank?
-
ec.cert.send_expiration_reminder(ec)
-
else
-
logger.error "blank expiration date for #{ec.cert.common_name}"
-
end
-
end
-
end
-
unless digest.empty?
-
digest.each do |d|
-
detect_abort
-
u_certs = d[1].map(&:cert).map(&:common_name).uniq.compact
-
begin
-
unless u_certs.empty?
-
logger.info "Sending reminder"
-
body = past ? Reminder.past_expired_digest_notice(d, interval) :
-
Reminder.digest_notice(d)
-
begin
-
body.deliver unless body.to.empty?
-
rescue Exception=>e
-
logger.error e.backtrace.inspect
-
end
-
end
-
d[1].each do |ec|
-
logger.info "create SentReminder"
-
SentReminder.create(trigger_value: [ec.before, ec.after].join(", "),
-
expires_at: ec.cert.expiration_date, signed_certificate_id:
-
ec.cert.id, subject: ec.cert.common_name,
-
body: body, recipients: d[0].split(",").last)
-
end
-
rescue Exception=>e
-
logger.error e.backtrace.inspect
-
raise e
-
end
-
end
-
end
-
end
-
-
1
def billing_monthly?
-
billing_method == 'monthly' || no_limit
-
end
-
-
1
def billing_daily?
-
billing_method == 'daily'
-
end
-
-
1
def invoice_required?
-
billing_monthly? || billing_daily? || no_limit
-
end
-
-
1
protected
-
-
1
def create_folders
-
99
archive_folder = Folder.find_or_create_by(
-
name: 'archived', archived: true, ssl_account_id: self.id
-
)
-
-
99
default_folder = Folder.find_by(
-
default: true, ssl_account_id: self.id
-
) || Folder.create(name: 'default', default: true, ssl_account_id: self.id)
-
-
99
expired_folder = Folder.find_or_create_by(
-
name: 'expired', expired: true, ssl_account_id: self.id
-
)
-
-
99
active_folder = Folder.find_or_create_by(
-
name: 'active', active: true, ssl_account_id: self.id
-
)
-
-
99
revoked_folder = Folder.find_or_create_by(
-
name: 'revoked', revoked: true, ssl_account_id: self.id
-
)
-
-
99
self.update_column(:default_folder_id, default_folder.id)
-
end
-
-
1
private
-
-
# creates dev db from production. NOTE: This will modify the db data so use this on a COPY of the production db
-
# SslAccount.convert_db_to_development
-
1
def self.convert_db_to_development(ranges=[["08/01/2016","09/01/2016"],["08/01/2017","09/01/2017"]],size=1000)
-
require "declarative_authorization/maintenance"
-
SentReminder.unscoped.delete_all
-
TrackedUrl.unscoped.delete_all
-
Tracking.unscoped.delete_all
-
VisitorToken.unscoped.delete_all
-
CaApiRequest.unscoped.delete_all
-
unless ranges.blank?
-
ranges.each do |range|
-
start,finish=range[0], range[1]
-
if start.is_a?(String)
-
s= start =~ /\// ? "%m/%d/%Y" : "%m-%d-%Y"
-
f= finish =~ /\// ? "%m/%d/%Y" : "%m-%d-%Y"
-
range[0] = Date.strptime start, s
-
range[1] = Date.strptime finish, f
-
end
-
end
-
%w(User SslAccount SiteSeal BillingProfile CertificateOrder Order DomainControlValidation
-
CertificateContent CertificateName Csr SignedCertificate Contact Validation ValidationHistory ValidationHistoryValidation
-
ValidationRulingValidationHistory Assignment Preference ShoppingCart SiteCheck Permission SystemAudit
-
ApiCredential CaApiRequest Reseller).each {|table|
-
sql = (['created_at BETWEEN ? AND ?']*ranges.count).join(" OR ")
-
table.constantize.unscoped.where.not(sql, *(ranges.flatten)).delete_all
-
}
-
end
-
ActiveRecord::Base.connection.tables.map do |model|
-
unless %w(auto_renewals delayed_job).include?(model)
-
begin
-
klass = model.capitalize.singularize.camelize.constantize
-
klass.where{created_at > from.days.ago}.delete_all
-
rescue
-
-
end
-
end
-
end
-
# Obfuscate IDs
-
i=100000
-
ApiCredential.unscoped.find_each(batch_size: size){|a|
-
a.update_columns account_key: i, secret_key: i
-
i+=1}
-
i=10000
-
SiteSeal.unscoped.find_each(batch_size: size){|s|
-
s.update_column :ref,i
-
i+=1}
-
# Obfuscate IDs
-
i=10000
-
SslAccount.class_eval do
-
def self.readonly_attributes
-
[]
-
end
-
end
-
SslAccount.unscoped.find_each(batch_size: size){|s|
-
s.acct_number=i
-
s.save validate: false
-
i+=1}
-
i=10000
-
# scramble usernames, emails
-
User.unscoped.find_each(batch_size: size) {|u|
-
u.update_columns(login: i, email: "test@#{i.to_s}.com")
-
u.password = "123456AsDF#"
-
u.save
-
i+=1
-
}
-
i=10000
-
CertificateOrder.unscoped.find_each(batch_size: size){|co|
-
co.ref = "co-"+i.to_s
-
co.external_order_number = "000000"
-
co.save
-
i+=1
-
}
-
i=10000
-
SignedCertificate.unscoped.find_each(batch_size: size){|sc|
-
sc.update_column :organization, (i+=1).to_s
-
}
-
i=10000
-
Csr.unscoped.find_each(batch_size: size){|c|
-
c.organization = i.to_s
-
c.organization_unit = i.to_s
-
c.state = i.to_s
-
c.locality = i.to_s
-
c.save
-
i+=1
-
}
-
i=10000
-
Order.unscoped.find_each(batch_size: size){|o|
-
o.update_column :reference_number, (i+=1).to_s
-
}
-
# obfuscate credit card numbers
-
BillingProfile.unscoped.find_each(batch_size: size){|bp|
-
bp.card_number="4222222222222"
-
bp.first_name = "Bob"
-
bp.last_name = "Spongepants"
-
bp.address_1 = "123 Houston St"
-
bp.address_2 = "Ste 100"
-
bp.company = "Company Inc"
-
bp.phone = "123456789"
-
bp.save}
-
# delete visitor tracking IDs,
-
# scramble user and contact e-mail addresses,
-
[Contact, Reseller].each { |klass| klass.unscoped.find_each(batch_size: size){|c|
-
c.first_name = "Bob"
-
c.last_name = "Spongepants#{c.id}"
-
c.email = "bob@spongepants#{c.id}.com"
-
c.company_name="Widgets#{c.id} Inc" if klass.method_defined? :company_name
-
c.company="Widgets#{c.id} Inc" if klass.method_defined? :company
-
c.organization="Widgets#{c.id} Inc" if klass.method_defined? :organization
-
c.website="www.widge#{c.id}.com" if klass.method_defined? :website
-
c.address1 = "123 Houston St"
-
c.address2 = "Ste #{c.id}"
-
c.phone = "#{c.id}"
-
c.fax = "#{c.id}"
-
c.save validate: false}}
-
CertificateOrder.unscoped.where{ssl_account_id==nil}.delete_all
-
has_sa = CertificateOrder.unscoped.joins{ssl_account}.pluck :id
-
all = CertificateOrder.unscoped.pluck :id
-
no_sa = all - has_sa
-
CertificateOrder.unscoped.where{id >> no_sa}.delete_all
-
# CertificateOrder.unscoped.select{|co|co.certificate_content.issued? && !co.certificate_content.expired? &&
-
# (co.certificate_content.csr.blank? || co.certificate_content.csr.signed_certificate.blank?)}.map(&:destroy)
-
end
-
-
1
SETTINGS_SECTIONS.each do |item|
-
3
define_method("#{item}_recipients_format") do
-
emails=[]
-
emails = eval("preferred_#{item}_recipients.split(' ')") unless
-
eval("preferred_#{item}_recipients.blank?")
-
errors.add("preferred_#{item}_recipients".to_sym,
-
'cannot be blank') if emails.empty?
-
results = emails.reject do |email|
-
email =~ /\A([^@\s]+)@((?:[-a-z0-9A-Z]+\.)+[a-zA-Z]{2,})\z/
-
end
-
errors.add("preferred_#{item}_recipients".to_sym,
-
'has invalid email addresses') unless (results.empty?)
-
end
-
end
-
-
1
def reminder_notice_destinations_format
-
emails = []
-
emails = preferred_reminder_notice_destinations.split(" ") unless
-
preferred_reminder_notice_destinations.blank?
-
errors.add(:preferred_reminder_notice_destinations,
-
'cannot be blank') if emails.empty?
-
results = emails.reject do |email|
-
email =~ /\A([^@\s]+)@((?:[-a-z0-9A-Z]+\.)+[a-zA-Z]{2,})\z/
-
end
-
errors.add(:preferred_reminder_notice_destinations,
-
'has invalid email addresses') unless (results.empty?)
-
end
-
-
1
def preferred_reminder_notice_triggers_format
-
109
NUMBER_OF_TRIGGERS.times do |i|
-
545
days = preferred_reminder_notice_triggers(ReminderTrigger.find(i+1))
-
545
unless days.blank?
-
(errors.add("reminder_notice_trigger #{(i+1).to_s}",
-
10
"must be an integer") unless !!(days=~/\d+/))
-
errors.add("reminder_notice_trigger #{(i+1).to_s}",
-
10
"must be in the range "+TRIGGER_RANGE.to_friendly) unless TRIGGER_RANGE.include?(days.to_i)
-
end
-
end
-
end
-
-
1
def renewed?(sc, renew_date)
-
eds=SignedCertificate.where(:common_name=>sc.common_name).
-
map(&:expiration_date).compact.sort
-
eds.detect do |ed|
-
ed > renew_date.days.from_now
-
end
-
end
-
-
1
def build_line_items(order)
-
#only do for prepaid, because 1-off certificate_orders when added are not
-
#necessarily paid for already
-
if !order.new_record? && order.line_items.all? {|c|c.sellable.try("is_prepaid?".to_sym) if c.sellable.respond_to?("is_prepaid?".to_sym)}
-
begin
-
OrderNotifier.certificate_order_prepaid(self, order).deliver
-
rescue Exception=>e
-
logger.error e.backtrace.inspect
-
end
-
order.line_items.each do |cert|
-
self.certificate_orders << cert.sellable
-
cert.sellable.pay!(true) unless cert.sellable.paid?
-
cc=cert.sellable.certificate_content
-
cc.save unless cc.ca.blank?
-
end
-
end
-
end
-
-
1
def self.remove_orphans
-
ids=User.pluck :ssl_account_id
-
SslAccount.where{id << ids}.delete_all
-
Preference.where{(owner_type=="SslAccount") & (owner_id << ids)}.delete_all
-
end
-
-
1
def self.quit?
-
q_pressed="Q pressed"
-
begin
-
#See if a 'Q' has been typed yet
-
while c = STDIN.read_nonblock(1)
-
logger.info q_pressed
-
puts q_pressed
-
return true if c == 'Q'
-
end
-
#No 'Q' found
-
false
-
rescue Errno::EINTR
-
false
-
rescue Errno::EAGAIN
-
# nothing was ready to be read
-
false
-
rescue EOFError
-
# quit on the end of the input stream
-
# (user hit CTRL-D)
-
true
-
end
-
end
-
-
#disable for deploying to cron
-
1
def self.detect_abort
-
#abort('Exit: user terminated') if Rails.env=~/production/i && quit?
-
end
-
end
-
1
class SslAccountUser < ActiveRecord::Base
-
1
belongs_to :user
-
1
belongs_to :unscoped_user, foreign_key: :ssl_account_id, class_name: "UnscopedUser"
-
1
belongs_to :ssl_account
-
-
1
scope :approved, ->{where{(approved == true) & (user_enabled == true)}}
-
1
scope :is_approved_ssl_account, ->(id){where{(approved == true) &
-
(user_enabled == true) & (ssl_account_id == id)}}
-
end
-
require 'net/http'
-
require 'net/https'
-
require 'open-uri'
-
-
class SslcomCaApi
-
-
# DV_ECC_SERVER_CERT is linked to the
-
# CertLockECCSSLsubCA
-
# SSLcom-SubCA-SSL-ECC-384-R2
-
# ManagementCA
-
-
SIGNATURE_HASH = %w(NO_PREFERENCE INFER_FROM_CSR PREFER_SHA2 PREFER_SHA1 REQUIRE_SHA2)
-
RESPONSE_TYPE={"zip"=>0,"netscape"=>1, "pkcs7"=>2, "individually"=>3}
-
RESPONSE_ENCODING={"base64"=>0,"binary"=>1}
-
-
PRODUCTION_IP = "192.168.5.17"
-
STAGING_IP = "192.168.5.19"
-
DEVELOPMENT_IP = "192.168.100.5"
-
-
# using the csr, determine the algorithm used
-
def self.sig_alg_parameter(csr)
-
case csr.sig_alg
-
when /rsa/i
-
"RSA"
-
when /ecdsa/i
-
"ECC"
-
when /dsa/i
-
"DSA"
-
end
-
end
-
-
# end entity profile details what will be in the certificate
-
def self.end_entity_profile(options)
-
if options[:mapping]
-
options[:mapping].end_entity
-
elsif options[:cc].certificate.is_evcs?
-
'EV_CS_CERT_EE'
-
elsif options[:cc].certificate.is_cs?
-
'CS_CERT_EE'
-
elsif options[:cc].certificate.is_dv?
-
'DV_SERVER_CERT_EE'
-
elsif options[:cc].certificate.is_ov?
-
'OV_SERVER_CERT_EE'
-
elsif options[:cc].certificate.is_ev?
-
'EV_SERVER_CERT_EE'
-
end unless options[:cc].certificate.blank?
-
end
-
-
def self.certificate_profile(options)
-
if options[:mapping]
-
options[:mapping].profile_name
-
elsif options[:cc].certificate.is_evcs?
-
"EV_RSA_CS_CERT"
-
elsif options[:cc].certificate.is_cs?
-
"RSA_CS_CERT"
-
else
-
"#{options[:cc].certificate.validation_type.upcase}_#{sig_alg_parameter(options[:cc].csr)}_SERVER_CERT"
-
end
-
end
-
-
def self.ca_name(options)
-
unless options[:cc].certificate.blank?
-
ca_name=if options[:mapping]
-
options[:mapping].ca_name
-
elsif options[:cc] and options[:cc].ca
-
options[:cc].ca.ca_name
-
elsif options[:ca]==Ca::CERTLOCK_CA
-
case options[:cc].certificate.product
-
when /^ev/
-
sig_alg_parameter(options[:cc].csr) =~ /rsa/i ? 'CertLock-SubCA-EV-SSL-RSA-4096' :
-
'CertLockEVECCSSLsubCA'
-
else
-
sig_alg_parameter(options[:cc].csr) =~ /rsa/i ? 'CertLock-SubCA-SSL-RSA-4096' :
-
'CertLockECCSSLsubCA'
-
end
-
elsif options[:ca]==Ca::SSLCOM_CA
-
case options[:cc].certificate.validation_type
-
when "ev"
-
sig_alg_parameter(options[:cc].csr) =~ /rsa/i ? 'SSLcom-SubCA-EV-SSL-RSA-4096-R3' :
-
'SSLcom-SubCA-EV-SSL-ECC-384-R2'
-
when "evcs"
-
'SSLcom-SubCA-EV-CodeSigning-RSA-4096-R3'
-
when "cs"
-
'SSLcom-SubCA-CodeSigning-RSA-4096-R1'
-
else
-
sig_alg_parameter(options[:cc].csr) =~ /rsa/i ? 'SSLcom-SubCA-SSL-RSA-4096' :
-
'SSLcom-SubCA-SSL-ECC-384-R2'
-
end
-
else
-
'ManagementCA'
-
end
-
Ca::SSL_ACCOUNT_MAPPING[options[:cc].ssl_account.acct_number] &&
-
Ca::SSL_ACCOUNT_MAPPING[options[:cc].ssl_account.acct_number][ca_name] ?
-
Ca::SSL_ACCOUNT_MAPPING[options[:cc].ssl_account.acct_number][ca_name] : ca_name
-
end
-
end
-
-
def self.subject_alt_name(options)
-
cert = options[:cc].certificate
-
common_name=options[:common_name]
-
names=if cert.is_smime?
-
"rfc822Name=#{options[:cc].certificate_order.get_recipient.email}"
-
elsif cert.is_server?
-
([common_name]+(options[:san] ?
-
options[:san].split(Certificate::DOMAINS_TEXTAREA_SEPARATOR) :
-
options[:cc].certificate_names.map(&:name))).uniq.map{|d|d.downcase}
-
end || ""
-
if cert.is_server?
-
names << if cert.is_wildcard?
-
"#{CertificateContent.non_wildcard_name(common_name)}"
-
elsif cert.is_single?
-
if common_name=~/\Awww\./
-
"#{common_name[4..-1]}"
-
else
-
"www.#{common_name}"
-
end
-
end
-
# replace dNSName= with iPAddress:1.2.3.4 for ip address
-
"dNSName=#{names.compact.map(&:downcase).uniq.join(",dNSName=")}"
-
else
-
names
-
end
-
end
-
-
# revoke json parameter string for REST call to EJBCA
-
def self.revoke_cert_json(signed_certificate, reason)
-
{issuer_dn: signed_certificate.openssl_x509.issuer.to_s.split("/").reject(&:empty?).join(","),
-
certificate_serial_number: signed_certificate.openssl_x509.serial.to_s(16).downcase,
-
revocation_reason: reason}.to_json
-
end
-
-
# retrieve json parameter string for REST call to EJBCA
-
# valid_only false means return also revoked and expired certs along with valid certs.
-
# true means only return valid certs
-
def self.retrieve_cert_json(options)
-
{user_name: options[:user_name]}.to_json
-
end
-
-
# create json parameter string for REST call to EJBCA
-
def self.issue_cert_json(options)
-
cert = options[:cc].certificate
-
co=options[:cc].certificate_order
-
carry_over=0
-
public_key=unless options[:public_key]
-
csr=options[:csr] ? Csr.new(body: options[:csr]) : options[:cc].csr
-
carry_over=(!cert.is_server? or cert.is_free?) ? 0 : csr.days_left
-
options[:mapping]=options[:mapping].ecc_profile if csr.sig_alg_parameter=~/ecc/i
-
csr.public_key
-
else
-
options[:public_key]
-
end
-
if public_key
-
dn={}
-
if options[:collect_certificate]
-
dn.merge! user_name: options[:username]
-
else
-
(options[:common_name] ||= options[:cn] ||
-
options[:cc].common_name) if cert.is_server?
-
options[:common_name]=options[:common_name].downcase if options[:common_name]
-
dn.merge! subject_dn: (options[:subject_dn] || options[:cc].subject_dn(options)),
-
ca_name: options[:ca_name] || ca_name(options),
-
certificate_profile: certificate_profile(options),
-
end_entity_profile: end_entity_profile(options),
-
subject_alt_name: subject_alt_name(options),
-
duration: "#{[(options[:duration] || co.remaining_days+(carry_over || 0)).to_i,
-
cert.max_duration].min.floor}:0:0"
-
dn.merge!(email_address: options[:cc].certificate_order.get_recipient.email) if cert.is_smime?
-
end
-
dn.merge!(request_type: "public_key",request_data: public_key.to_pem) if
-
options[:collect_certificate] or options[:no_public_key].blank?
-
dn.to_json
-
end
-
end
-
-
def self.set_mapping(certificate_order,options)
-
options[:mapping] = Ca.find_by_ref(options[:send_to_ca]) if options[:send_to_ca]
-
options[:mapping] = certificate_order.certificate_content.ca if options[:mapping].blank?
-
-
# does this need to be a DV if OV is required but not satisfied?
-
if certificate_order.certificate.is_server? and
-
(options[:mapping].profile_name=~/OV/ or options[:mapping].is_ev?)
-
downstep = !certificate_order.ov_validated?
-
options[:mapping]=options[:mapping].downstep if downstep
-
end
-
end
-
-
def self.apply_for_certificate(certificate_order, options={})
-
set_mapping(certificate_order, options)
-
options.merge! cc: cc = options[:certificate_content] || certificate_order.certificate_content
-
begin
-
if cc.csr.blank?
-
cc.create_csr(body: options[:csr])
-
else
-
cc.csr.save if cc.csr.new_record?
-
end
-
if options[:mapping].is_ev?
-
approval_req, approval_res = SslcomCaApi.get_status(csr: cc.csr, mapping: options[:mapping])
-
return cc.csr.sslcom_ca_requests.create(
-
parameters: approval_req.body, method: "get", response: approval_res.body,
-
ca: options[:ca]) if approval_res.try(:body)=~/WAITING FOR APPROVAL/
-
end
-
if options[:mapping].is_ev? and (approval_res.try(:body).blank? or approval_res.try(:body)=="[]" or
-
(!cc.signed_certificate.blank? and cc.signed_certificate.read_attribute(:ejbca_username)==cc.csr.sslcom_ca_requests.compact.first.username and
-
!cc.csr.sslcom_ca_requests.compact.first.username.blank?))
-
# create the user for EV order
-
host = ca_host(options[:mapping])+"/v1/user"
-
options.merge! no_public_key: true
-
else # collect cert
-
if cc.pending_issuance?
-
return
-
else
-
cc.pend_issuance!
-
end unless options[:mapping].is_ev?
-
host = ca_host(options[:mapping])+
-
"/v1/certificate#{'/ev' if options[:mapping].is_ev?}/pkcs10"
-
options.merge!(collect_certificate: true, username:
-
cc.csr.sslcom_usernames.compact.first) if options[:mapping].is_ev?
-
end
-
req, res = call_ca(host, options, issue_cert_json(options))
-
api_log_entry=cc.csr.sslcom_ca_requests.create(request_url: host,
-
parameters: req.body, method: "post", response: res.try(:body), ca: options[:ca_name] || ca_name(options))
-
cc.validate! if cc.pending_issuance? # release hold
-
if (!options[:mapping].is_ev? and api_log_entry.username.blank?) or
-
(options[:mapping].is_ev? and api_log_entry.username.blank? and
-
api_log_entry.request_username.blank?)
-
OrderNotifier.problem_ca_sending("support@ssl.com", cc.certificate_order,"sslcom").deliver
-
elsif api_log_entry.certificate_chain # signed certificate is issued
-
cc.update_column(:label, options[:mapping].is_ev? ? api_log_entry.request_username :
-
api_log_entry.username) unless api_log_entry.blank?
-
attrs = {body: api_log_entry.end_entity_certificate.to_s, ca_id: options[:mapping].id,
-
ejbca_username: cc.csr.sslcom_ca_requests.compact.first.username}
-
cc.csr.signed_certificates.create(attrs)
-
SystemAudit.create(
-
owner: options[:current_user],
-
target: api_log_entry,
-
notes: "issued signed certificate for certificate order #{certificate_order.ref}",
-
action: "SslcomCaApi#apply_for_certificate"
-
)
-
end
-
api_log_entry
-
ensure
-
cc.validate! if cc.pending_issuance?
-
end
-
end
-
-
def self.ca_host(mapping=nil)
-
mapping ? mapping.host : Rails.application.secrets.sslcom_ca_host
-
end
-
-
def self.generate_for_certificate(options={})
-
host = ca_host(options[:mapping]) + "/v1/certificate/pkcs10"
-
req, res = call_ca(host, {}, issue_cert_json(options))
-
-
api_log_entry = options[:cc].csr.sslcom_ca_requests.create(request_url: host, parameters: req.body,
-
method: 'post', response: res.try(:body), ca: options[:ca_name] || ca_name(options))
-
-
unless api_log_entry.username
-
OrderNotifier.problem_ca_sending("support@ssl.com", options[:cc].certificate_order,"sslcom").deliver
-
else
-
options[:cc].update_column(:ref, api_log_entry.username) unless api_log_entry.blank?
-
# options[:cc].csr.signed_certificates.create body: api_log_entry.end_entity_certificate.to_s, ca_id: options[:ca_id]
-
end
-
-
api_log_entry.end_entity_certificate
-
end
-
-
def self.revoke_ssl(signed_certificate, reason)
-
if signed_certificate.is_sslcom_ca?
-
host = ca_host(signed_certificate.certificate_content.ca)+"/v1/certificate/revoke"
-
req, res = call_ca(host, {}, revoke_cert_json(signed_certificate, SslcomCaRevocationRequest::REASONS[0]))
-
api_log_entry=signed_certificate.sslcom_ca_revocation_requests.create(request_url: host,
-
parameters: req.body, method: "post", response: res.message, ca: "sslcom")
-
unless api_log_entry.response=="OK"
-
OrderNotifier.problem_ca_sending("support@ssl.com", signed_certificate.certificate_order,"sslcom").deliver
-
end
-
api_log_entry
-
end
-
end
-
-
def self.get_status(options={csr: nil,host_only: false})
-
unless options[:csr].blank?
-
approval=options[:csr].sslcom_approval_ids.compact.first
-
return if approval.blank?
-
query="status/#{approval}"
-
else
-
query="approvals"
-
end
-
host = ca_host(options[:csr] ? options[:csr].certificate_content.ca : options[:mapping])+"/v1/#{query}"
-
if options[:host_only]
-
host
-
else
-
options={method: "get"}
-
body = ""
-
call_ca(host, options, body)
-
end
-
end
-
-
def self.unique_id(approval_id)
-
req,res = get_status
-
body=JSON.parse(res.body)
-
id=body.select{|approval|approval[1]==approval_id.to_i} unless body.blank?
-
id.first[0] unless id.blank?
-
end
-
-
def self.client_certs(host)
-
case host
-
when PRODUCTION_IP
-
[Rails.application.secrets.ejbca_production_client_auth_cert,
-
Rails.application.secrets.ejbca_production_client_auth_key]
-
when DEVELOPMENT_IP
-
[Rails.application.secrets.ejbca_development_client_auth_cert,
-
Rails.application.secrets.ejbca_development_client_auth_key]
-
when STAGING_IP
-
[Rails.application.secrets.ejbca_staging_client_auth_cert,
-
Rails.application.secrets.ejbca_staging_client_auth_key]
-
else
-
[Rails.application.secrets.ejbca_production_client_auth_cert,
-
Rails.application.secrets.ejbca_production_client_auth_key]
-
end
-
end
-
-
private
-
-
# body - parameters in JSON format
-
def self.call_ca(host, options, body)
-
uri = URI.parse(host)
-
client_auth_cert,client_auth_key=client_certs(uri.host)
-
req = (options[:method]=~/GET/i ? Net::HTTP::Get : Net::HTTP::Post).new(uri, 'Content-Type' => 'application/json')
-
http = Net::HTTP.new(uri.host, uri.port)
-
http.use_ssl = true
-
http.read_timeout = 1200 # Default is 60 seconds
-
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
-
http.cert = OpenSSL::X509::Certificate.new(File.read(client_auth_cert))
-
http.key = OpenSSL::PKey::RSA.new(File.read(client_auth_key))
-
req.body = body
-
res = http.request(req)
-
return req, res
-
end
-
-
-
# def self.test
-
# ssl_util = Savon::Client.new "http://ccm-host/ws/EPKIManagerSSL?wsdl"
-
# begin
-
# response = ssl_util.enroll do |soap|
-
# soap.body = {:csr => csr}
-
# end
-
# rescue
-
-
# client = Savon::Client.new do |wsdl, http|
-
# wsdl.document = "http://ccm-host/ws/EPKIManagerSSL?wsdl"
-
# end
-
# client.wsdl.soap_actions
-
# end
-
end
-
-
# This class represent requests sent to the SSL.com CA. It's assumed the content-type is JSON
-
-
class SslcomCaRequest < CaApiRequest
-
after_initialize do
-
if new_record? and !self.response.blank?
-
parsed=JSON.parse(self.response)
-
self.username = parsed["user_name"] || parsed["username"]
-
self.approval_id = parsed["approval_id"]
-
self.certificate_chain = parsed["certificate_chain"] || parsed["certificates"]
-
if self.username.blank? and !self.parameters.blank?
-
parsed_req=JSON.parse(self.parameters)
-
self.username = parsed_req["user_name"] || parsed_req["username"]
-
end
-
end
-
end
-
-
scope :unexpired, ->{where{created_at > 48.hours.ago}}
-
-
def pkcs7
-
certs=OpenSSL::PKCS7.new(SignedCertificate.enclose_with_tags(certificate_chain))
-
add_this=Certificate.xcert_certum(certs.certificates.last,true)
-
add_certum=add_this!=certs.certificates.last.to_s
-
appended_certificates=if add_certum
-
[OpenSSL::X509::Certificate.new(add_this),
-
OpenSSL::X509::Certificate.new(SignedCertificate.enclose_with_tags(Certificate::CERTUM_ROOT))]
-
else
-
[OpenSSL::X509::Certificate.new(add_this)]
-
end
-
certs.certificates=certs.certificates[0..-2]+appended_certificates
-
certs
-
end
-
-
def x509_certificates
-
pkcs7.certificates
-
end
-
-
def end_entity_certificate
-
x509_certificates.first
-
end
-
-
def username
-
read_attribute(:username) || ((JSON.parse(self.response)["user_name"] ||
-
JSON.parse(self.response)["username"]) unless self.response.blank?)
-
end
-
-
def request_username
-
(JSON.parse(self.parameters)["user_name"] || JSON.parse(self.response)["username"]) unless self.parameters.blank?
-
end
-
-
def approval_id
-
read_attribute(:approval_id) || (JSON.parse(self.response)["approval_id"] unless self.response.blank?)
-
end
-
-
def certificate_chain
-
read_attribute(:certificate_chain) || (JSON.parse(self.response)["certificate_chain"] unless self.response.blank?)
-
end
-
-
def call_again
-
SslcomCaApi.call_ca(request_url,{},parameters)
-
end
-
end
-
# This class represent revocations requests sent to the SSL.com CA. It's assumed the content-type is JSON
-
-
class SslcomCaRevocationRequest < CaApiRequest
-
REASONS = %w(UNSPECIFIED)
-
-
# REASONS = %w(UNSPECIFIED KEYCOMPROMISE CACOMPROMISE AFFILIATIONCHANGED SUPERSEDED CESSATIONOFOPERATION
-
# CERTIFICATEHOLD REMOVEFROMCRL PRIVILEGESWITHDRAWN AACOMPROMISE)
-
#
-
end
-
# Represents smaller 'buyable' sub units to a main order. Basically a buyable version of ProductVariantItem that can be
-
# linked to an Order and CertificateOrder
-
# ie duration and domains are sub units of a certificate order
-
-
class SubOrderItem < ActiveRecord::Base
-
belongs_to :sub_itemable, :polymorphic => true
-
belongs_to :product_variant_item
-
belongs_to :product
-
acts_as_sellable :cents => :amount, :currency => false
-
end
-
1
require "net/https"
-
1
require "uri"
-
1
require "digest/sha1"
-
-
1
class Surl < ActiveRecord::Base
-
1
belongs_to :user
-
1
has_many :surl_visits
-
-
1
validate :url_format
-
1
validates :guid, uniqueness: true, on: :create
-
1
validates :username, length: {within: 6..50}, presence: true, :if => :perform_username_validation?
-
1
validates :password, length: {within: 6..20}, presence: true, :if => :perform_password_validation?
-
-
1
attr_accessor :password
-
1
attr_accessor :set_access_restrictions
-
-
1
REDIRECTED="redirect"
-
1
RENDERED="render"
-
1
BLACKLISTED="blacklisted"
-
1
LOOP_ERROR="Trying to confuse us? Sorry, but ssl links pointing to ssl.com are not allowed,
-
otherwise we'll loop forever."
-
1
SUBDOMAIN="links"
-
1
TIMEOUT_DURATION=10
-
# TIMEOUT_CAA_CHECK_DURATION=30
-
1
RETRIES=2
-
1
COOKIE_VERSION=1
-
1
COOKIE_NAME=:links2
-
1
DISABLED_STATUS="disabled"
-
1
REDIRECT_FILES= %w(ACE AIF ANI API ART AVI BIN BMP BUD BZ2 CAT CBT CDA CDT CHM CLP CMD CMF CUR DAO
-
DAT DD DEB DEV DIR DLL DOC DOT DRV DS DWG DXF EMF EML EPS EPS2 EXE FFL FFO FLA FNT GIF GID GRP
-
GZ HEX HLP HT HQX ICL ICM ICO JAR JPEG JPG LAB LGO LIT LOG LSP MAQ MAR MDB MDL MID MOD MOV MP3 MP4
-
MPEG MPP MSG MSG NCF NLM O OCX ODT OGG OST PAK PCL PCT PDF PDR PIF PL PM3 PM4 PM5 PM6 PNG POL POT
-
PPD PPS PPT PRN PS PSD PSP PST PUB PWL QIF QT RAM RAR RAW RDO REG RM RPM RSC RTF SCR SEA SGML SH
-
SIT SMD SVG SWF SWP SYS TAR TGA TIFF TIF TMP TTF TXT UDF UUE VBX VM VXD WAV WMF WRI WSZ XCF XIF
-
XIF XIF XLS XLT XML XSL ZIP)
-
-
1
REMOVE="remove"
-
-
1
if Rails.env=='development'
-
URL = 'ssl.com:3000'
-
else
-
1
URL = 'ssl.com'
-
end
-
-
# before_create
-
1
before_save :tasks_on_save
-
1
after_initialize :default_values#, :prep
-
1
after_create do |s|
-
s.update_attributes identifier: s.id.encode62
-
end
-
-
1
default_scope{ where{status >> [nil, DISABLED_STATUS]}.order(:created_at.desc)}
-
-
1
def access_granted(surl)
-
username==surl.username && valid_password?(surl.password)
-
end
-
-
# Returns true if the password passed matches the password in the DB
-
1
def valid_password?(password)
-
self.password_hash == self.class.hash_password(password, self.password_salt)
-
end
-
-
1
def is_http?
-
original =~ /\Ahttp/
-
end
-
-
1
def to_param
-
guid
-
end
-
-
1
def full_link
-
"http#{'s' if require_ssl}://ssl.com/#{identifier}"
-
end
-
-
1
def uri
-
original.gsub(" ", "")
-
end
-
-
1
private
-
1
def default_values
-
if new_record?
-
self.share ||= false
-
self.require_ssl ||= false
-
self.guid ||= UUIDTools::UUID.random_create.to_s
-
self.set_access_restrictions ||= "0"
-
end
-
prep
-
end
-
-
1
def prep
-
unless username.blank? && password.blank?
-
self.set_access_restrictions="1"
-
else
-
self.username, self.password = [nil,nil]
-
end
-
end
-
-
1
def tasks_on_save
-
if(perform_password_validation?)
-
hash_password
-
elsif(set_access_restrictions=="0")
-
self.username, self.password, self.password_hash, self.password_salt = [nil,nil,nil,nil]
-
end
-
end
-
-
#validation method to make sure the submitted url is http, https, or ftp
-
1
def url_format
-
unless [URI::HTTP, URI::HTTPS, URI::FTP].find {|url_type| URI.parse(original).kind_of?(url_type)}
-
errors.add :original, "is an invalid url. Please be sure it begins with http://, https://, or ftp://"
-
else
-
errors.add(:original, Surl::LOOP_ERROR) if URI.parse(original).host =~ /\Assl.com\z/i
-
end
-
rescue Exception=>e
-
logger.error("Error in Surl#url_format: #{e.message}")
-
end
-
-
# Performs the actual password encryption. You want to change this salt to something else.
-
1
def self.hash_password(password, salt)
-
Digest::SHA1.hexdigest(password+salt)
-
end
-
-
# Sets the hashed version of self.password to password_hash, unless it's blank.
-
1
def hash_password
-
self.password_salt=SecureRandom.base64(8)
-
self.password_hash = self.class.hash_password(self.password,self.password_salt) unless self.password.blank?
-
end
-
-
# Assert whether or not the password validations should be performed. Always on new records, only on existing
-
# records if the .password attribute isn't blank.
-
1
def perform_password_validation?
-
set_access_restrictions=="1" && (new_record? ? true : !(password.blank? && !password_hash.blank?))
-
end
-
-
1
def perform_username_validation?
-
set_access_restrictions=="1"
-
end
-
end
-
class SurlBlacklist < ActiveRecord::Base
-
end
-
class SurlVisit < ActiveRecord::Base
-
belongs_to :surl
-
belongs_to :visitor_token
-
end
-
module SurlsToSslGs
-
def self.initialize
-
tables=%w(Customer Order Certificate OrderNumber Merchant MerchantContact
-
OrdersShoppingCart)
-
tables.each do |t|
-
tc = ('OldSite::'+t).constantize
-
source_tables=V2MigrationProgress.all.select {|p|
-
p.source_table_name==tc.table_name} || []
-
#if the number of records on the source table has change, then migrate
-
#those records again
-
unless tc.count==source_tables.count
-
source_tables.each {|sc|sc.delete}
-
tc.find_each do |o|
-
V2MigrationProgress.create(:source_table_name=>tc.table_name,
-
:source_id=>o.source_obj_id)
-
end
-
end
-
end
-
end
-
-
#this function is preferable to initialize because it does not delete existing
-
#records and instead just adds new ones
-
def self.dynamic_initialize
-
tables=%w(Customer Order Certificate OrderNumber Merchant MerchantContact
-
OrdersShoppingCart)
-
V2MigrationProgress.remove_migratable_orphans
-
tables.each do |t|
-
OldSite.detect_abort
-
ap "looking for new records for #{t}"
-
tc = ('OldSite::'+t).constantize
-
V2MigrationProgress.remove_legacy_orphans(tc)
-
source_tables=V2MigrationProgress.select(:source_id).where(:source_table_name.eq => tc.table_name) || []
-
#if the number of records on the source table has change, then add the new
-
#records
-
unless tc.count==source_tables.count
-
legacy_ids=tc.source_ids
-
ap ["legacy count: #{tc.count.to_s}", "migration progress count: #{source_tables.count.to_s}"].join(", ")
-
missing = legacy_ids-source_tables.map(&:source_id)
-
tc.where(tc.primary_key.to_sym + missing).each do |o|
-
ap "creating V2MigrationProgress for #{tc.table_name+'_'+o.send(tc.primary_key).to_s}"
-
V2MigrationProgress.create(:source_table_name=>tc.table_name,
-
:source_id=>o.source_obj_id)
-
end
-
else
-
ap "no new records found for #{t}"
-
end
-
end
-
end
-
-
# this is the main function to do the migration
-
def self.migrate_all
-
Authorization.ignore_access_control(true)
-
ActiveRecord::Base.logger.level = 3 # at any time
-
ap "Usage: type 'Q' and press Enter to exit this program"
-
dynamic_initialize
-
Customer.migrate_all
-
Order.migrate_all
-
Customer.sync_attributes_with_v2
-
::DuplicateV2User.make_latest_login_primary
-
Certificate.sync_certs
-
#verify all LineItems have a sellable or else delete them
-
LineItem.all.each{|l|l.destroy if l.sellable.blank?}
-
self.adjust_site_seals_workflow
-
self.adjust_certificate_order_prepaid
-
self.adjust_certificate_content_workflow
-
end
-
-
def self.certs_and_line_items_mismatch
-
ActiveRecord::Base.logger.level = 3 # at any time
-
i=0
-
OldSite::Order.find_each(:include=>{:order_number=>
-
[{:certificates=>{:certificate_product=>:product}},
-
:orders_shopping_carts]}) do |o|
-
ids=[]
-
o.order_number.orders_shopping_carts.each do |osc|
-
ids<<osc.order_number.certificates.map(&:product).map(&:ProductID)
-
end
-
if ids.uniq.count>1
-
p 'Error! '+o.OrderNumber
-
logger.error 'Certificate products mismatch for order: '+o.OrderNumber
-
else
-
p [ids, "count: #{i+=1}, OrderID: #{o.OrderNumber}"]
-
end
-
end
-
end
-
-
#just a one-time-use convenience method. The logic fix was incorporated into
-
#the migration script
-
def self.adjust_user_profile_info
-
OldSite::Customer.find_each do |c|
-
u=V2MigrationProgress.find_by_source(c).migratable
-
(u.updated_at=c.updated_at
-
u.first_name= c.FirstName
-
u.last_name = c.LastName
-
u.update_record_without_timestamping) unless u.blank?
-
end
-
end
-
-
#just a one-time-use convenience method. The logic fix was incorporated into
-
#the migration script
-
def self.adjust_order_payment_method
-
ActiveRecord::Base.logger.level = 3 # at any time
-
::Order.find_each do |o|
-
old_o=V2MigrationProgress.find_by_migratable_and_source_table_name(o,
-
"Orders", :first)
-
unless old_o.blank?
-
old_o.source_obj.copy_payment_method_to(o)
-
o.save
-
end
-
end
-
end
-
-
#just a one-time-use convenience method. Just trying to import skipped
-
#signed certificates
-
def self.import_signed_certificates
-
Authorization.ignore_access_control(true)
-
ActiveRecord::Base.logger.level = 3 # at any time
-
i=0
-
count = ::Csr.count
-
::Csr.find_each do |c|
-
cert = c.certificate_content.try(:migrated_from)
-
cert = cert.last unless cert.blank?
-
unless cert.blank?
-
p ["#{i+=1} of #{count}, CertificateID: #{cert.CertificateID}"]
-
if c.signed_certificate.blank? && !cert.SignedCert.blank?
-
c.signed_certificate_by_text=cert.SignedCert
-
if c.signed_certificate
-
c.signed_certificate.update_attribute(:created_at,
-
cert.ReadyNoticeSentToCustomer)
-
c.certificate_content.workflow_state='issued'
-
else
-
c.certificate_content.workflow_state='csr_submitted'
-
msg="Error: Could not import signed certificate
-
from Old::Certificate#{cert.CertificateID}"
-
logger.error msg
-
p msg
-
end
-
c.save
-
end
-
end
-
end
-
end
-
-
#just a one-time-use convenience method. The logic fix was incorporated into
-
#the migration script
-
def self.adjust_signed_certificate_created_at
-
SignedCertificate.find_each do |sc|
-
sc.update_attribute :created_at, sc.csr.certificate_content.created_at
-
end
-
end
-
-
#just a one-time-use convenience method. The logic fix was incorporated into
-
#the migration script
-
def self.adjust_server_type
-
::CertificateContent.find_each do |cc|
-
if cc.server_software.blank?
-
unless V2MigrationProgress.find_by_migratable(cc).blank?
-
c=V2MigrationProgress.find_by_migratable(cc).source_obj
-
cc.created_at=c.SubmitDate
-
cc.server_software=OldSite::ServerType.server_software(
-
c.ServerType)
-
cc.save(false)
-
end
-
end
-
end
-
end
-
-
#just a one-time-use convenience method. The logic fix was incorporated into
-
#the migration script
-
def self.adjust_line_items
-
Authorization.ignore_access_control(true)
-
CertificateOrder.find_each do |co|
-
if co.order
-
oscs=V2MigrationProgress.find_by_migratable co.order, :all
-
unless oscs.empty?
-
o=oscs.find{|osc|osc.source_obj.is_a? OrdersShoppingCart}.source_obj
-
if o
-
items=o.orders_kit_carts.each_with_object([]) do |okc, arry|
-
arry << okc.KitItemName
-
end
-
co.v2_line_items=items unless items.empty?
-
co.line_item_qty=1
-
co.save
-
end
-
end
-
end
-
end
-
end
-
-
#one time function to correct misplaced v2_migration_progress from users to duplicate_v2_users
-
def self.update_v2_migrations_for_duplicate_users
-
migs = DuplicateV2User.all
-
created = migs.map(&:created_at)
-
dups=[]
-
dup_tmp=created.each{|c|dups<<c if created.count(c) > 1} #find duplicates
-
dup_created_at=migs.select{|c|c.created_at==dup_tmp[0]}
-
migs-=dup_created_at
-
migs_h = Hash[migs.map{|m|[m.created_at.to_s, m]}] #hash migrated dups using created_at.to_s as key
-
oc=OldSite::Customer.select("CustomerID, CreatedOn")
-
oc_h=Hash[oc.map{|o|[o.CreatedOn.to_s, o]}] #hash legacy users using CreatedOn.to_s as key
-
migs_h.merge!(oc_h){|key, old, new|[new, old]}
-
non_matched=migs_h.select{|k,v|!v.is_a?(Array)}
-
non_matched.each{|k,v|migs_h.delete(k)}
-
migs_h.each do |k,v|
-
mp=v[0].v2_migration_progress
-
mp.migratable=v[1]
-
mp.save
-
end
-
end
-
-
#DEPRECATED - see OldSite::Customer.sync_attributes_with_v2
-
#user changes such as passwords or emails (or even logins) are sync using this method
-
def self.sync_changed_users
-
d = DuplicateV2User.all
-
v2_users = V2MigrationProgress.where(:migratable_type =~ "User").map(&:migratable).uniq
-
#get all migrated users into array
-
migs=d+v2_users
-
created = migs.map(&:created_at)
-
dups=[]
-
dup_tmp=created.each{|c|dups<<c if created.count(c) > 1} #find duplicates
-
dup_created_at=migs.select{|c|c.created_at==dup_tmp[0]}
-
migs-=dup_created_at
-
migs_h = Hash[migs.map{|m|[m.created_at.to_s, m]}] #hash migrated users/dups using created_at.to_s as key
-
oc=OldSite::Customer.select("Email, UserName, Password, CreatedOn")
-
oc_h=Hash[oc.map{|o|[o.CreatedOn.to_s, o]}] #hash legacy users using CreatedOn.to_s as key
-
migs_h.merge!(oc_h){|key, old, new|[new, old]}
-
non_matched=migs_h.select{|k,v|!v.is_a?(Array)}
-
non_matched.each{|k,v|migs_h.delete(k)}
-
changed=migs_h.select do |k,v|
-
v[1].email!=v[0].Email || (v[1].is_a?(User) ? v[1].crypted_password : v[1].password)!=v[0].Password ||
-
v[1].login!=v[0].UserName
-
end
-
msgs=[]
-
changed.each do |k,v|
-
msgs<< "changes detected for #{v[1].model_and_id}"
-
if v[1].email!=v[0].Email
-
msgs<< "email changed from #{v[1].email} to #{v[0].Email}"
-
v[1].update_attribute :email, v[0].Email
-
end
-
if (v[1].is_a?(User) ? v[1].crypted_password : v[1].password)!=v[0].Password
-
msgs<< "password changed from #{v[1].is_a?(User) ? v[1].crypted_password : v[1].password} to #{v[0].Password}"
-
v[1].update_attribute (v[1].is_a?(User) ? :crypted_password : :password), v[0].Password
-
end
-
if v[1].login!=v[0].UserName
-
msgs<< "login changed from #{v[1].login} to #{v[0].UserName}"
-
v[1].update_attribute :login, v[0].UserName
-
end
-
end
-
ap msgs
-
#oc_created_at=oc.map(&:CreatedOn)
-
#oc_s=oc_created_at.sort.map(&:to_s)
-
#ca_s=created.sort.map(&:to_s)
-
#diff_s=oc_s-ca_s
-
end
-
-
def self.sync_duplicate_v2_user_attributes
-
DuplicateV2User.sync_mismatched_attributes if DuplicateV2User.mismatched_attributes.blank?
-
if DuplicateV2User.mismatched_attributes.blank?
-
"successfully synced DuplicateV2User attributes"
-
else
-
"failed syncing DuplicateV2User attributes"
-
end
-
end
-
-
def self.adjust_certificate_content_workflow
-
CertificateContent.find_each(:include=>
-
[:registrant,:certificate_contacts, {:csr=>:signed_certificates}]) do |cc|
-
if V2MigrationProgress.find_by_migratable_id_and_migratable_type cc.id,
-
'CertificateContent'
-
csr = cc.csr
-
cert = csr.try(:signed_certificate)
-
registrant = cc.registrant
-
contacts = cc.certificate_contacts
-
if cert
-
cc.update_attribute :workflow_state, 'issued'
-
elsif !contacts.empty?
-
cc.update_attribute :workflow_state, 'contacts_provided'
-
elsif registrant
-
cc.update_attribute :workflow_state, 'info_provided'
-
elsif csr
-
cc.update_attribute :workflow_state, 'csr_submitted'
-
else
-
cc.update_attribute :workflow_state, 'new'
-
end
-
end
-
end
-
end
-
-
def self.adjust_certificate_order_prepaid
-
CertificateOrder.find_each(:include=>[:orders, :certificate_contents]) do |co|
-
if co.order.try("preferred_migrated_from_v2?")
-
if co.workflow_state=='paid' && co.certificate_content.blank?
-
co.preferred_payment_order = 'prepaid'
-
co.save
-
end
-
end
-
end
-
end
-
-
def self.adjust_site_seals_workflow
-
SiteSeal.find_each(:include=>
-
{:certificate_orders=>[:certificate_contents, :orders]}) do |ss|
-
unless ss.certificate_order.blank? || ss.certificate_order.order.blank?
-
state = ss.certificate_order.certificate_content.workflow_state if
-
ss.certificate_order && ss.certificate_order.certificate_content
-
case state
-
when 'issued'
-
ss.update_attribute :workflow_state,
-
SiteSeal::FULLY_ACTIVATED.to_s
-
when 'new'
-
ss.update_attribute :workflow_state, 'new'
-
else
-
ss.update_attribute :workflow_state,
-
SiteSeal::CONDITIONALLY_ACTIVATED.to_s
-
end
-
ss.update_seal_type
-
end
-
end
-
end
-
-
# we need to verify at the data level that migration integrity has been maintained
-
# compare non-duplicate user accounts and their orders and certificates
-
# then compare duplicates
-
def self.verify_migration_integrity
-
# for each v1 user, find the corresponding v2 user
-
# compare orders quantity and prices
-
# compare csrs and signed certificates (quantity and contents)
-
# we'll start off with non dupllicates and verify 1-to-1 mappings to orders
-
[].tap do |order_count_mismatch|
-
i=0
-
nd=OldSite::Customer.non_duplicates
-
p "total #{nd.count.to_s} legacy users to process"
-
nd.find_each do |c|
-
# need to get v2 user
-
p "processed #{i.to_s} legacy users" if i%100==0
-
user = c.migratable
-
if user.is_a?(User) && user.ssl_account
-
if user.cached_ssl_account.orders.count == c.orders.count
-
#user.ssl_account.orders.each do |o|
-
# o
-
#end
-
else
-
order_count_mismatch << user
-
p "#{user.login} (#{user.mode_and_id}) doesn't have the same number of orders as the legacy user"
-
end
-
end
-
i+=1
-
end
-
end
-
#OldSite::Customer.duplicates.find_each do |c|
-
# # need to get v2 user
-
# user = c.migratable.class == User ? c.migratable : c.migratable.user
-
# user.ssl_account.orders.count >= c.orders.count
-
#end
-
end
-
-
class Base < ActiveRecord::Base
-
establish_connection :ssl_gs
-
self.abstract_class=true
-
-
def self.source_ids
-
key = self.primary_key.to_sym
-
select(key).map(&key)
-
end
-
-
def source_obj_id
-
send(self.class.primary_key)
-
end
-
-
end
-
-
class X3User < Base
-
set_table_name 'x3_users'
-
set_primary_key 'id'
-
def self.pk_sym
-
primary_key.to_sym
-
end
-
end
-
-
class X3Link < Base
-
set_table_name 'x3_links'
-
set_primary_key 'id'
-
def self.pk_sym
-
primary_key.to_sym
-
end
-
-
def self.migrate
-
Surl.where{(id > 7) & (original != nil)}.find_each{|s|
-
X3Link.create(short_url: "http://ssl.gs/"+s.identifier,
-
long_url: s.original, adtype: "Interstitial",
-
post_date: s.created_at,
-
title: "Get paid to shorten and share links at ssl.gs",
-
views: 0,
-
earned: BigDecimal(0),
-
user: 0
-
)
-
}
-
end
-
end
-
end if Rails.env=='development' && MIGRATING_SURLS_TO_SSL_GS
-
-
# Used to audit actions of users or actors (owner) on targets
-
-
1
class SystemAudit < ActiveRecord::Base
-
1
belongs_to :owner, :polymorphic => true
-
1
belongs_to :target, :polymorphic => true
-
1
acts_as_sellable :cents => :amount, :currency => false
-
end
-
class Tag < ActiveRecord::Base
-
belongs_to :ssl_account
-
has_many :taggings, dependent: :destroy
-
has_many :orders, through: :taggings, source: :taggable, source_type: 'Order'
-
has_many :certificate_orders, through: :taggings,
-
source: :taggable, source_type: 'CertificateOrder'
-
has_many :certificate_contents, through: :taggings,
-
source: :taggable, source_type: 'CertificateContent'
-
-
before_validation :strip_tag_name
-
-
validates :name, allow_nil: false, allow_blank: false,
-
length: { minimum: 1, maximum: 255 },
-
uniqueness: {
-
case_sensitive: true,
-
scope: :ssl_account_id,
-
message: 'Tag already exists for this team.'
-
}
-
-
def self.update_for_model(object, tags_list=[])
-
@object = object
-
if tags_list.blank? || tags_list.empty?
-
clear_tags
-
else
-
get_object_team
-
current_tags = get_tag_names
-
@remove_tags = current_tags - tags_list
-
@new_tags = tags_list - current_tags
-
-
remove_tags
-
add_tags
-
end
-
end
-
-
def self.get_all_tag_names(target_object)
-
target_object.tags.pluck(:name)
-
end
-
-
def self.get_object_team_tags(target_object)
-
get_object_team(target_object)
-
get_team_tags.order(taggings_count: :desc)
-
end
-
-
def self.filter_popular_tags(tags, type=:order)
-
tags.joins(:taggings)
-
.where.not(taggings_count: 0)
-
.where(taggings:
-
{
-
taggable_type: (type == :order ? 'Order' : ['CertificateOrder', 'CertificateContent'])
-
}
-
).uniq
-
end
-
-
def get_name_format
-
name.length > 16 ? "#{name[0..16]}..." : name
-
end
-
-
private
-
-
def self.get_object_team(target_object=nil)
-
@object = target_object unless target_object.nil?
-
@team = @object.is_a?(Order) ? @object.billable : @object.ssl_account
-
end
-
-
def self.remove_tags
-
@object.taggings.where(
-
tag_id: get_team_tags.where(name: @remove_tags).ids
-
).destroy_all
-
end
-
-
def self.add_tags
-
if @new_tags.any?
-
found_team_tags = get_team_tags.where(name: @new_tags)
-
@new_team_tags = @new_tags - found_team_tags.pluck(:name)
-
-
add_tags_to_team
-
-
@object.tags << (
-
found_team_tags + get_team_tags.where(name: @new_team_tags)
-
).flatten.uniq
-
end
-
end
-
-
def self.add_tags_to_team
-
@new_team_tags.each do |name|
-
current_tag = Tag.new(name: name, ssl_account_id: @team.id)
-
@team.tags << current_tag if current_tag.valid?
-
end
-
end
-
-
def self.get_tag_names
-
@object.tags.pluck(:name)
-
end
-
-
def self.clear_tags
-
@object.tags.destroy_all
-
end
-
-
def self.get_team_tags
-
@team.tags
-
end
-
-
def strip_tag_name
-
name = name.strip unless name.nil?
-
end
-
end
-
class Tagging < ActiveRecord::Base
-
belongs_to :tag
-
belongs_to :taggable, polymorphic: true
-
-
before_create :unique_taggings
-
after_create :increment_tag
-
after_destroy :decrement_tag
-
-
validates :tag_id, :taggable_type, :taggable_id,
-
presence: true, allow_blank: false, allow_nil: false
-
-
private
-
-
def unique_taggings
-
self.errors.clear
-
-
dup = Tagging.where(
-
taggable_type: taggable_type, taggable_id: taggable_id, tag_id: tag_id
-
).any?
-
self.errors.add(:tag, message: "Duplicate tag.") if dup
-
end
-
-
def increment_tag
-
tag.increment!(:taggings_count)
-
end
-
-
def decrement_tag
-
tag.decrement!(:taggings_count)
-
end
-
end
-
class TechnicalContact < CertificateContact
-
end
-
class TrackedUrl < ActiveRecord::Base
-
has_many :trackings
-
has_many :visitor_tokens, :through=>:trackings
-
end
-
class Tracking < ActiveRecord::Base
-
belongs_to :visitor_token
-
belongs_to :tracked_url
-
belongs_to :referer, :class_name => "TrackedUrl", :foreign_key => "referer_id"
-
-
def parents
-
Tracking.where{(referer_id == my{tracked_url_id}) & (visitor_token_id == my{visitor_token_id}) &
-
(created_at < my{created_at})}.sort{|a,b|a.created_at.to_i<=>b.created_at.to_i}
-
end
-
-
def parent
-
parents.last if parents
-
end
-
-
def parent_root
-
parents.first if parents
-
end
-
-
SSL_LINKS = ["/", "http://ssl.com%", "https://ssl.com%", "http://secure.ssl.com%", "https://secure.ssl.com%",
-
"https://ssl/", "http://reseller.ssl.com%", "https://reseller.ssl.com%","http://staging1.ssl.com%",
-
"http://sws.ssl.com%", "https://sws.ssl.com%","http://staging.ssl.com%", "https://staging1.ssl.com%",
-
"http://staging2.ssl.com%", "https://staging2.ssl.com%",
-
"http://www.cms.ssl.com%", "https://www.cms.ssl.com%",
-
"http://www.fnl.ssl.com%", "https://www.fnl.ssl.com%",
-
"http://links.ssl.com%", "https://links.ssl.com%",
-
"http://info.ssl.com%", "https://info.ssl.com%"]
-
-
scope :non_ssl_com_url, lambda{joins{tracked_url}.where{tracked_urls.url.not_like_all SSL_LINKS}}
-
scope :non_ssl_com_referer, lambda{joins{referer}.where{referer.url.not_like_all SSL_LINKS}}
-
scope :affiliate_referers, lambda {|affid|
-
joins{tracked_url}.where{tracked_urls.url =~ "%/code/#{affid}%"}
-
}
-
-
end
-
class U2f < ActiveRecord::Base
-
belongs_to :user
-
end
-
class UnscopedUser < User
-
self.default_scopes = []
-
end
-
class Unsubscribe < ActiveRecord::Base
-
validates :email, presence: true, email: true, :uniqueness=>
-
{:scope=>[:domain]}, on: :create
-
validates :specs, presence: true, on: :create
-
validates :domain, presence: true, on: :create
-
validates :ref, presence: true, on: :create
-
-
ALL="all"
-
ONLY="only"
-
-
before_validation do |un|
-
un.ref ||='un-'+SecureRandom.hex(1)+Time.now.to_i.to_s(32)
-
end
-
end
-
require 'net/http'
-
require 'uri'
-
-
class UrlCallback < ActiveRecord::Base
-
belongs_to :callbackable, polymorphic: true
-
-
AUTH = {basic: 'basic'}
-
METHODS = {get: 'get', post: 'post'}
-
-
validates :url, presence: true, format: /\Ahttps?:\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/i
-
validates :method, inclusion:
-
{in: METHODS.values, message: "needs to be one of the following: #{METHODS.values.join(', ')}"}
-
# validates :auth, inclusion:
-
# {in: AUTH.values, message: "needs to be one of the following: #{AUTH.values.join(', ')}"}
-
validate :auth_validation, if: lambda {|cb|cb.auth}
-
serialize :parameters
-
serialize :headers
-
serialize :auth
-
-
-
before_validation {
-
# self.auth = self.auth.downcase
-
self.method = self.method.downcase
-
}
-
-
after_initialize do
-
if new_record?
-
self.method ||= METHODS[:get]
-
end
-
end
-
-
def auth_validation
-
unless auth.is_a?(Hash)
-
errors[:auth] << "expecting hash"
-
return false
-
end
-
errors.add(:auth, "needs to be one of the following: #{AUTH.values.join(', ')}") unless AUTH.values.include?(self.auth.keys.last)
-
if auth[:basic]
-
errors.add("auth.basic".to_sym, "must have username for basic auth") unless auth[:basic].keys.include? 'username'
-
errors.add("auth.basic".to_sym, "must have password for basic auth") unless auth[:basic].keys.include? 'password'
-
end
-
end
-
-
def perform_callback(options={})
-
UrlCallback.perform_callback(self,options)
-
end
-
-
def self.perform_callback(url_callback,options)
-
begin
-
uri = URI.parse(url_callback.url)
-
req = url_callback.method==METHODS[:post] ? Net::HTTP::Post.new(uri, 'Content-Type' =>
-
(url_callback.headers and url_callback.headers["content-type"]) ?
-
url_callback.headers["content-type"] : 'application/json') : Net::HTTP::Get.new(uri)
-
req.basic_auth url_callback.auth["basic"]["username"],
-
url_callback.auth["basic"]["username"] if (url_callback.auth and url_callback.auth["basic"])
-
http = Net::HTTP.new(uri.host, uri.port)
-
if url_callback.url=~/^https/i
-
http.use_ssl = true
-
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
-
end
-
req.body = if url_callback.parameters['certificate_hook']
-
cert_param = url_callback.parameters['certificate_hook'] || "certificate_hook"
-
url_callback.parameters.delete('certificate_hook')
-
url_callback.parameters.merge(cert_param=>eval(options[:certificate_hook].gsub!("null","nil")))
-
else
-
url_callback.parameters.merge(certificate_hook: eval(options[:certificate_hook].gsub!("null","nil")))
-
end.to_json
-
res = http.request(req)
-
if res.code == "301"
-
res = Net::HTTP.get_response_with_redirect(URI.parse(res.header['location']))
-
end
-
return req, res
-
rescue Exception=>e
-
return false
-
end
-
end
-
end
-
1
class User < ActiveRecord::Base
-
1
extend Memoist
-
1
include V2MigrationProgressAddon
-
1
include UserMessageable
-
# using_access_control
-
-
1
OWNED_MAX_TEAMS = 3
-
1
PASSWORD_SPECIAL_CHARS = '~`!@#\$%^&*()-+={}[]|;:"<>,./?'
-
-
1
has_many :u2fs
-
1
has_many :assignments, dependent: :destroy
-
1
has_many :visitor_tokens
-
1
has_many :surls
-
1
has_many :roles, :through => :assignments
-
1
has_many :permissions, :through => :roles
-
1
has_many :legacy_v2_user_mappings, :as=>:user_mappable
-
1
has_many :duplicate_v2_users
-
1
has_many :other_party_requests
-
1
has_many :client_applications
-
1
has_many :owned_system_audits, as: :owner, class_name: "SystemAudit"
-
1
has_many :target_system_audits, as: :target, class_name: "SystemAudit"
-
1
has_many :tokens, ->{order("authorized_at desc").includes(:client_application)}, :class_name => "OauthToken"
-
1
has_many :ssl_account_users, dependent: :destroy
-
1
has_many :ssl_accounts, through: :ssl_account_users
-
1
has_many :certificate_orders, through: :ssl_accounts
-
1
has_many :orders, through: :ssl_accounts
-
1
has_many :validation_histories, through: :certificate_orders
-
1
has_many :validations, through: :certificate_orders
-
7
has_many :approved_ssl_account_users, ->{where{(approved == true) & (user_enabled == true)}},
-
dependent: :destroy, class_name: "SslAccountUser"
-
1
has_many :approved_ssl_accounts,
-
foreign_key: :ssl_account_id, source: "ssl_account", through: :approved_ssl_account_users
-
1
has_many :approved_teams,
-
foreign_key: :ssl_account_id, source: "ssl_account", through: :approved_ssl_account_users
-
1
has_many :refunds
-
1
has_many :discounts, as: :benefactor, dependent: :destroy
-
1
has_one :shopping_cart
-
1
has_and_belongs_to_many :user_groups
-
1
has_many :notification_groups, through: :ssl_accounts
-
1
has_many :certificate_order_tokens
-
-
1
preference :managed_certificate_row_count, :string, :default=>"10"
-
1
preference :registered_agent_row_count, :string, :default=>"10"
-
1
preference :cert_order_row_count, :string, :default=>"10"
-
1
preference :order_row_count, :string, :default=>"10"
-
1
preference :cdn_row_count, :string, :default=>"10"
-
1
preference :user_row_count, :string, :default => "10"
-
1
preference :note_group_row_count, :string, :default => "10"
-
1
preference :scan_log_row_count, :string, :default => "10"
-
1
preference :domain_row_count, :string, :default => "10"
-
1
preference :domain_csr_row_count, :string, :default => "10"
-
1
preference :team_row_count, :string, :default => "10"
-
1
preference :validate_row_count, :string, :default => "10"
-
-
#will_paginate
-
1
cattr_accessor :per_page
-
1
@@per_page = 10
-
-
1
attr_accessor :changing_password, :admin_update, :role_ids, :role_change_type
-
1
attr_accessible :login, :email, :password, :password_confirmation,
-
:openid_identifier, :status, :assignments_attributes, :first_name, :last_name,
-
:default_ssl_account, :ssl_account_id, :role_ids, :role_change_type,
-
:main_ssl_account, :max_teams, :persist_notice
-
1
validates :email, email: true, uniqueness: true, #TODO look at impact on checkout
-
format: {with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create}
-
1
validates :password, format: {
-
with: /\A(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[\W]).{8,}\z/, if: :validate_password?,
-
message: "must be at least 8 characters long and include at least 1 of each of the following: uppercase, lowercase, number and special character such as #{User::PASSWORD_SPECIAL_CHARS}"
-
}
-
1
accepts_nested_attributes_for :assignments
-
-
1
acts_as_messageable
-
-
1
acts_as_authentic do |c|
-
1
c.logged_in_timeout = 30.minutes
-
1
c.validate_email_field = false
-
1
c.session_ids = [nil, :shadow]
-
1
c.crypto_provider = Authlogic::CryptoProviders::Sha512
-
1
c.validates_length_of_password_field_options =
-
{:on => :update, :minimum => 8,
-
:if => '(has_no_credentials? && !admin_update) || changing_password'}
-
1
c.validates_length_of_password_confirmation_field_options =
-
{:on => :update, :minimum => 8,
-
:if => '(has_no_credentials? && !admin_update) || changing_password'}
-
end
-
-
1
before_save :should_reset_perishable_token
-
-
1
before_create do |u|
-
98
u.status='enabled'
-
98
u.max_teams = OWNED_MAX_TEAMS unless u.max_teams
-
end
-
-
1929
default_scope {where{status << ['disabled']}.order("users.created_at desc")}
-
1
scope :with_role, -> (role){joins(:roles).where('lower(roles.name) LIKE (?)',
-
"%#{role.downcase.strip}%")}
-
1
scope :search, -> (term){joins{ssl_accounts.api_credentials}.where{
-
(login =~ "%#{term}%") |
-
(email =~ "%#{term}%") |
-
(last_login_ip =~ "%#{term}%") |
-
(current_login_ip =~ "%#{term}%") |
-
(ssl_accounts.api_credentials.account_key =~ "%#{term}%") |
-
(ssl_accounts.api_credentials.secret_key =~ "%#{term}%") |
-
(ssl_accounts.acct_number =~ "%#{term}%")}.uniq}
-
-
1
scope :search_sys_admin, ->{ joins{ roles }.where{ roles.name == Role::SYS_ADMIN } }
-
-
1
scope :search_super_user, -> {joins{roles}.where{roles.name == Role::SUPER_USER}}
-
-
1
def ssl_account(default_team=nil)
-
90
SslAccount.find_by_id(Rails.cache.fetch("#{cache_key}/ssl_account/#{default_team.is_a?(Symbol) ? default_team.to_s : default_team.try(:cache_key)}") do
-
20
default_ssl = default_ssl_account && is_approved_account?(default_ssl_account)
-
20
main_ssl = main_ssl_account && is_approved_account?(main_ssl_account)
-
-
# Retrieve team that was manually set as default in Teams by user
-
20
break main_ssl_account if (default_team && main_ssl)
-
-
20
if default_ssl
-
20
default_ssl_account
-
elsif !default_ssl && main_ssl
-
set_default_ssl_account main_ssl_account
-
main_ssl_account
-
else
-
approved_account = get_first_approved_acct
-
set_default_ssl_account(approved_account) if approved_account
-
approved_account
-
end
-
end)
-
end
-
1
memoize :ssl_account
-
-
1
def is_approved_account?(target_ssl)
-
20
Rails.cache.fetch("#{cache_key}/is_approved_account/#{target_ssl.try(:cache_key)}") do
-
20
return false unless SslAccount.exists?(target_ssl)
-
20
ssl_account_users.where(ssl_account_id: target_ssl, user_enabled: true, approved: true).any?
-
end
-
end
-
1
memoize "is_approved_account?".to_sym
-
-
1
def is_main_account?(ssl_account)
-
return false if main_ssl_account.nil?
-
ssl_account.id == main_ssl_account
-
end
-
-
1
def is_account_owner?(ssl_account)
-
total_teams_owned.include?(ssl_account)
-
end
-
-
1
def is_account_team_admin?(ssl_account)
-
total_teams_admin.include?(ssl_account)
-
end
-
-
1
def is_team_owner_admin?(ssl_account)
-
assignments.where(role_id: [Role.get_owner_id, Role.get_account_admin_id], ssl_account_id: ssl_account.id).size > 0
-
end
-
-
1
def role_symbols_archived_team(ssl_account)
-
assignments.includes(:role).where(ssl_account_id: ssl_account.id).map{|assign| assign.role.name.to_sym}.uniq.compact
-
end
-
-
1
def is_first_approved_acct?(ssl_account)
-
ssl_account == get_first_approved_acct
-
end
-
-
1
def owned_ssl_account
-
total_teams_owned.first
-
end
-
-
1
def team_status(team)
-
5
ssl = ssl_account_users.where(ssl_account_id: team.id).uniq.compact.first
-
5
if ssl
-
5
status = :accepted if active && ssl.approved
-
5
status = :declined if ssl.declined_at || (!ssl.approved && ssl.token_expires.nil? && ssl.approval_token.nil?)
-
5
status = :expired if ssl.token_expires && (status != :declined) && (ssl.token_expires < DateTime.now)
-
5
status = :pending if !active && (status != :declined)
-
5
status = :pending if active && (!ssl.approved && ssl.token_expires && ssl.approval_token) && (ssl.token_expires > DateTime.now)
-
end
-
5
status
-
end
-
-
1
def is_duo_required?
-
is_super_user?
-
end
-
-
1
def is_passed_2fa session_duo
-
status = false
-
if self.is_duo_required?
-
status = session_duo
-
else
-
if self.ssl_account.sec_type == 'duo'
-
if Settings.duo_auto_enabled || Settings.duo_custom_enabled
-
status = session_duo
-
else
-
status = true
-
end
-
else
-
status = true
-
end
-
end
-
status
-
end
-
-
1
def get_auto_add_users_teams
-
self.ssl_accounts.joins(:assignments).where(
-
assignments: {role_id: Role.can_auto_add_users}
-
).uniq.compact
-
end
-
-
1
def get_auto_add_users
-
users = User.joins(:ssl_accounts)
-
.where(ssl_accounts: {id: get_auto_add_users_teams.map(&:id)})
-
.where.not(users: {id: id}).uniq.compact
-
end
-
-
1
def get_auto_add_user_roles(added_user)
-
role_ids = added_user.assignments.where(
-
ssl_account_id: get_auto_add_users_teams.map(&:id)
-
).pluck(:role_id).uniq
-
-
# If invited user has owner role or reseller role, then replace
-
# it with account admin role for the team they're invited to.
-
if role_ids.include?(Role.get_owner_id) ||
-
role_ids.include?(Role.get_reseller_id)
-
-
# User cannot be account_admin and have other roles.
-
role_ids = [Role.get_account_admin_id]
-
end
-
role_ids.uniq
-
end
-
-
1
def total_teams_owned(user_id=nil)
-
2
user = self_or_other(user_id)
-
2
user.assignments.includes(:ssl_account).where(role_id: Role.get_owner_id).map(&:ssl_account).uniq.compact
-
end
-
1
memoize :total_teams_owned
-
-
1
def total_teams_admin(user_id = nil)
-
user = self_or_other(user_id)
-
user.assignments.includes(:ssl_account).where(role_id: Role.get_account_admin_id).map(&:ssl_account).uniq.compact
-
end
-
1
memoize :total_teams_admin
-
-
1
def total_teams_can_manage_users(user_id=nil)
-
1
user = self_or_other(user_id)
-
1
user.assignments.includes(:ssl_account).where(role_id: Role.can_manage_users).map(&:ssl_account).uniq.compact
-
end
-
1
memoize :total_teams_can_manage_users
-
-
1
def total_teams_cannot_manage_users(user_id=nil)
-
user = self_or_other(user_id)
-
user.ssl_accounts - user.assignments.where(role_id: Role.cannot_be_managed)
-
.map(&:ssl_account).uniq.compact
-
end
-
1
memoize :total_teams_cannot_manage_users
-
-
1
def max_teams_reached?(user_id=nil)
-
2
user = self_or_other(user_id)
-
2
total_teams_owned(user.id).count >= user.max_teams
-
end
-
-
1
def set_default_team(ssl_account)
-
3
update(main_ssl_account: ssl_account.id) if ssl_accounts.include?(ssl_account)
-
end
-
-
1
def can_manage_team_users?(target_ssl=nil)
-
assignments.where(
-
ssl_account_id: (target_ssl.nil? ? ssl_account : target_ssl).id,
-
role_id: Role.can_manage_users
-
).any?
-
end
-
-
1
def self.find_non_owners
-
[].tap do |orphans|
-
find_each do |u|
-
orphans << u if u.owned_ssl_account.blank?
-
end
-
end
-
end
-
-
1
def create_ssl_account(role_ids=nil, attr={})
-
91
self.save if self.new_record?
-
91
new_ssl_account = SslAccount.create(attr)
-
91
ssl_accounts << new_ssl_account
-
91
set_roles_for_account(new_ssl_account, role_ids) if (role_ids && role_ids.length > 0)
-
91
set_default_ssl_account(new_ssl_account) unless default_ssl_account
-
91
approve_account(ssl_account_id: new_ssl_account.id)
-
91
new_ssl_account
-
end
-
-
1
def set_default_ssl_account(account)
-
84
account = account.is_a?(SslAccount) ? account.id : account
-
84
update_attribute(:default_ssl_account, account)
-
end
-
-
1
def clear_default_ssl_account
-
update_attribute(:default_ssl_account, nil)
-
end
-
-
1
def set_roles_for_account(account, role_ids)
-
95
if account && ssl_accounts.include?(account) && role_ids.count > 0
-
91
role_ids.each do |role|
-
92
Assignment.find_or_create_by(
-
user_id: id,
-
role_id: role,
-
ssl_account_id: account.id
-
)
-
end
-
end
-
end
-
-
1
def roles_for_account(target_ssl=nil)
-
4
ssl = target_ssl.nil? ? ssl_account : target_ssl
-
4
if ssl_accounts.include?(ssl)
-
2
assignments.where(ssl_account_id: ssl).pluck(:role_id).uniq
-
else
-
2
[]
-
end
-
end
-
1
memoize :roles_for_account
-
-
1
def get_roles_by_name(role_name)
-
2
role_id = Role.get_role_id(role_name)
-
2
role_id ? assignments.where(role_id: role_id) : []
-
end
-
-
1
def update_account_role(account, old_role, new_role)
-
1
old_role = assignments.where(
-
ssl_account_id: account, role_id: Role.get_role_id(old_role)
-
).first
-
1
unless duplicate_role?(new_role, account)
-
old_role.update(role_id: Role.get_role_id(new_role)) if old_role
-
end
-
end
-
-
1
def duplicate_role?(role, target_ssl=nil)
-
1
assignments.where(
-
1
ssl_account_id: (target_ssl.nil? ? ssl_account : target_ssl).id,
-
role_id: (role.is_a?(String) ? Role.get_role_id(role): Role.find(role))
-
).any?
-
end
-
-
1
def invite_user_to_account!(params)
-
user_exists = User.get_user_by_email(params[:user][:email])
-
user_exists ? user_exists : invite_new_user(params)
-
end
-
-
1
def invite_new_user(params)
-
1
if params[:deliver_invite]
-
User.get_user_by_email(params[:user][:email])
-
.deliver_signup_invitation!(params[:from_user], params[:root_url], params[:invited_teams])
-
else
-
1
user = User.new(params[:user].merge(login: params[:user][:email]))
-
1
user.signup!(params)
-
1
ssl = user.create_ssl_account([Role.get_owner_id])
-
1
user.update_attribute(:main_ssl_account, ssl.id) if ssl
-
1
user.update_attribute(:persist_notice, true)
-
-
# Check Code Signing Certificate Order for assign as assignee.
-
1
if Settings.require_signup_password
-
1
CertificateOrder.unscoped.search_validated_not_assigned(user.email).each do |cert_order|
-
cert_order.update_attribute(:assignee, user)
-
LockedRecipient.create_for_co(cert_order)
-
end
-
end
-
-
1
user
-
end
-
end
-
-
1
def invite_existing_user(params)
-
email = params[:user][:email] if params[:user]
-
ssl_acct_id = (params[:user] && params[:user][:ssl_account_id]) || params[:ssl_account_id]
-
user = email ? User.get_user_by_email(email) : self
-
new_params = params.merge(ssl_account_id: ssl_acct_id, skip_match: true, from_user: params[:from_user])
-
-
if user.ssl_accounts.map(&:id).include? ssl_acct_id.to_i
-
user.set_approval_token(new_params)
-
if user.approval_token_valid?(new_params)
-
user.deliver_invite_to_account!(new_params)
-
user.deliver_invite_to_account_notify_admin!(new_params)
-
end
-
end
-
end
-
-
1
def user_exists_for_account?(user_email, target_ssl=nil)
-
ssl = target_ssl.nil? ? ssl_account : target_ssl
-
user = User.get_user_by_email(user_email)
-
user && SslAccountUser.where(user_id: user, ssl_account_id: ssl).any?
-
end
-
-
1
def remove_user_from_account(account, current_user)
-
assignments.where(ssl_account_id: account).delete_all
-
ssl = ssl_account_users.where(ssl_account_id: account).delete_all
-
if ssl > 0
-
deliver_removed_from_account!(account, current_user)
-
unless current_user.is_system_admins?
-
deliver_removed_from_account_notify_admin!(account, current_user)
-
end
-
update_default_ssl_account(account)
-
end
-
end
-
-
1
def leave_team(remove_ssl)
-
unless remove_ssl.get_account_owner == self
-
ssl = ssl_account_users.where(ssl_account_id: remove_ssl).delete_all
-
assignments.where(ssl_account_id: remove_ssl).delete_all
-
end
-
if ssl && ssl > 0
-
update_default_ssl_account(remove_ssl)
-
deliver_leave_team!(remove_ssl)
-
Assignment.where( # notify team owner and users_manager(s)
-
ssl_account_id: remove_ssl,
-
role_id: Role.get_role_ids([Role::OWNER, Role::USERS_MANAGER])
-
).map(&:user).uniq.compact.each do |notify|
-
deliver_leave_team_notify_admins!(notify, remove_ssl)
-
end
-
end
-
end
-
-
1
def update_default_ssl_account(remove_ssl)
-
if default_ssl_account == remove_ssl.id
-
if main_ssl_account != remove_ssl.id
-
update(default_ssl_account: main_ssl_account)
-
else
-
ssl = get_first_approved_acct
-
update_attributes(default_ssl_account: ssl.id, main_ssl_account: ssl.id)
-
end
-
end
-
update(main_ssl_account: default_ssl_account) if main_ssl_account == remove_ssl.id
-
end
-
-
1
def self.get_user_by_email(email)
-
current_user = User.where('lower(email) = ?', email.strip.downcase)
-
current_user.any? ? current_user.first : nil
-
end
-
-
1
def manageable_users
-
ssl_account.cached_users
-
end
-
-
1
def manageable_acs
-
ssl_account.api_credentials
-
end
-
-
1
def has_role?(role)
-
roles.map{|r|r.name.downcase}.include?(role.to_s)
-
end
-
-
1
def active?
-
167
active
-
end
-
-
1
def is_disabled?(target_ssl=nil)
-
70
Rails.cache.fetch("#{cache_key}/is_disabled/#{target_ssl.try(:cache_key)}") do
-
70
ssl = target_ssl || ssl_account
-
70
return true if ssl.nil?
-
ssl_account_users.where(ssl_account_id: ssl.id)
-
.map(&:user_enabled).include?(false)
-
end
-
end
-
-
1
def is_admin_disabled?
-
Rails.cache.fetch("#{cache_key}/is_admin_disabled}") do
-
!ssl_account_users.map(&:user_enabled).include?(true)
-
end
-
end
-
-
1
def deliver_activation_confirmation_by_sysadmin!(password)
-
reset_perishable_token!
-
UserNotifier.activation_confirmation_by_sysadmin(self, password).deliver
-
end
-
-
1
def deliver_auto_activation_confirmation!
-
reset_perishable_token!
-
UserNotifier.auto_activation_confirmation(self).deliver
-
end
-
-
1
def deliver_activation_instructions!
-
reset_perishable_token!
-
UserNotifier.activation_instructions(self).deliver
-
end
-
-
1
def deliver_activation_confirmation!
-
reset_perishable_token!
-
UserNotifier.activation_confirmation(self).deliver
-
end
-
-
1
def deliver_signup_invitation!(current_user, root_url, invited_teams)
-
reset_perishable_token!
-
UserNotifier.signup_invitation(self, current_user, root_url, invited_teams).deliver
-
end
-
-
1
def deliver_password_reset_instructions!
-
reset_perishable_token!
-
UserNotifier.password_reset_instructions(self).deliver
-
end
-
-
1
def deliver_username_reminder!
-
UserNotifier.username_reminder(self).deliver
-
end
-
-
1
def deliver_password_changed!
-
UserNotifier.password_changed(self).deliver
-
end
-
-
1
def deliver_email_changed!(address=self.email)
-
UserNotifier.email_changed(self, address).deliver
-
end
-
-
1
def deliver_invite_to_account!(params)
-
UserNotifier.invite_to_account(self, params[:from_user], params[:ssl_account_id]).deliver
-
end
-
-
1
def deliver_invite_to_account_notify_admin!(params)
-
UserNotifier.invite_to_account_notify_admin(self, params[:from_user], params[:ssl_account_id]).deliver
-
end
-
-
1
def deliver_removed_from_account!(account, current_user)
-
UserNotifier.removed_from_account(self, account, current_user).deliver
-
end
-
-
1
def deliver_removed_from_account_notify_admin!(account, current_user)
-
UserNotifier.removed_from_account_notify_admin(self, account, current_user).deliver
-
end
-
-
1
def deliver_leave_team!(account)
-
UserNotifier.leave_team(self, account).deliver
-
end
-
-
1
def deliver_leave_team_notify_admins!(notify_user, account)
-
UserNotifier.leave_team_notify_admins(self, notify_user, account).deliver
-
end
-
-
1
def deliver_invite_to_account_accepted!(account, for_admin=nil)
-
UserNotifier.invite_to_account_accepted(self, account, for_admin).deliver
-
end
-
-
1
def deliver_invite_to_account_disabled!(account, current_user)
-
UserNotifier.invite_to_account_disabled(self, account, current_user).deliver
-
end
-
-
1
def deliver_ssl_cert_private_key!(resource_id, host_name, custom_domain_id)
-
UserNotifier.ssl_cert_private_key(self, resource_id, host_name, custom_domain_id).deliver
-
end
-
-
1
def deliver_generate_install_ssl!(resource_id, host_name, to_address)
-
UserNotifier.generate_install_ssl(self, resource_id, host_name, to_address).deliver
-
end
-
-
1
def deliver_register_ssl_manager_to_team!(registered_agent_ref, ssl_account, auto_approve)
-
auto_approve ?
-
UserNotifier.auto_register_ssl_manager_to_team(self, ssl_account).deliver :
-
UserNotifier.register_ssl_manager_to_team(self, registered_agent_ref, ssl_account).deliver
-
end
-
-
1
def browsing_history(l_bound=nil, h_bound=nil, sort="asc")
-
l_bound = "01/01/2000" if l_bound.blank?
-
s= l_bound =~ /\// ? "%m/%d/%Y" : "%m-%d-%Y"
-
start = Date.strptime l_bound, s
-
finish =
-
if(h_bound.blank?)
-
DateTime.now
-
elsif h_bound.is_a?(String)
-
f= h_bound =~ /\// ? "%m/%d/%Y" : "%m-%d-%Y"
-
Date.strptime h_bound, f
-
else
-
h_bound.to_datetime
-
end
-
count=0
-
visitor_tokens.map do |vt|
-
["route #{count+=1}"]+
-
vt.trackings.order("created_at "+sort).where{created_at >> (start..finish)}.map{|t| "from #{t.referer.url.blank? ? "unknown" : t.referer.url} to #{t.tracked_url.url} at #{t.created_at}"}.uniq
-
end
-
end
-
-
# find user with no ssl_account
-
1
def ssl_account_orphans
-
User.where{ssl_account_id.not_in SslAccount.all}
-
end
-
-
# we need to make sure that either a password or openid gets set
-
# when the user activates his account
-
1
def has_no_credentials?
-
4
self.crypted_password.blank? #&& self.openid_identifier.blank?
-
end
-
-
# ...
-
# now let's define a couple of methods in the user model. The first
-
# will take care of setting any data that you want to happen at signup
-
# (aka before activation)
-
1
def signup!(params)
-
1
assign_roles(params)
-
1
self.login = params[:user][:login] if login.blank?
-
1
self.email = params[:user][:email]
-
-
# TODO: New logic for auto activation account by passing password on Signup page.
-
1
if Settings.require_signup_password
-
1
self.password = params[:user][:password] unless params[:user][:password].blank?
-
1
self.password_confirmation = params[:user][:password_confirmation] unless params[:user][:password_confirmation].blank?
-
1
self.active = true unless params[:user][:password].blank?
-
end
-
-
1
save_without_session_maintenance
-
end
-
-
1
def assign_roles(params)
-
1
role_ids = params[:user][:role_ids]
-
1
cur_account_id = params[:user][:ssl_account_id]
-
1
unless role_ids.nil? || cur_account_id.nil?
-
new_role_ids = role_ids.compact.reject{|id| id.blank?}.map(&:to_i)
-
end
-
1
if new_role_ids.present?
-
current_account = SslAccount.find cur_account_id
-
current_role_ids = roles_for_account current_account
-
new_role_ids = new_role_ids - current_role_ids
-
set_roles_for_account(current_account, new_role_ids.uniq)
-
end
-
end
-
-
1
def remove_roles(params, inverse=false)
-
new_role_ids = params[:user][:role_ids].compact.reject{|id| id.blank?}.map(&:to_i)
-
current_role_ids = roles_for_account(SslAccount.find(params[:user][:ssl_account_id]))
-
removable_role_ids = inverse ? new_role_ids : current_role_ids - new_role_ids
-
-
assignments.where(
-
role_id: removable_role_ids,
-
ssl_account_id: params[:user][:ssl_account_id]
-
).destroy_all
-
end
-
-
1
class << self
-
1
extend Memoist
-
1
def roles_list_for_user(user, exclude_roles=nil)
-
2
exclude_roles ||= []
-
2
unless user.is_system_admins?
-
2
exclude_roles << Role.where.not(id: Role.get_select_ids_for_owner).map(&:id).uniq
-
end
-
2
exclude_roles.any? ? Role.where.not(id: exclude_roles.flatten) : Role.all
-
end
-
1
memoize :roles_list_for_user
-
-
1
def get_user_accounts_roles(user)
-
# e.g.: {17198:[4], 29:[17, 18], 15:[17, 18, 19, 20]}
-
Rails.cache.fetch("#{user.cache_key}/get_user_accounts_roles") do
-
user.ssl_accounts.inject({}) do |all, s|
-
all[s.id] = user.assignments.where(ssl_account_id: s.id).pluck(:role_id).uniq
-
all
-
end
-
end
-
end
-
1
memoize :get_user_accounts_roles
-
-
1
def get_user_accounts_roles_names(user)
-
# e.g.: {'team_1': ['owner'], 'team_2': ['account_admin', 'installer']}
-
Rails.cache.fetch("#{user.cache_key}/get_user_accounts_roles_names") do
-
user.ssl_accounts.inject({}) do |all, s|
-
all[s.get_team_name] = user.assignments.where(ssl_account_id: s.id)
-
.map(&:role).uniq.map(&:name)
-
all
-
end
-
end
-
end
-
1
memoize :get_user_accounts_roles_names
-
-
1
def total_teams_owned(user_id)
-
User.find(user_id).assignments.includes(:ssl_account).where(role_id: Role.get_owner_id).map(&:ssl_account).uniq.compact
-
end
-
1
memoize :total_teams_owned
-
end
-
-
-
# the second will take care of setting any data that you want to happen
-
# at activation. at the very least this will be setting active to true
-
# and setting a pass, openid, or both.
-
1
def activate!(params)
-
self.active = true
-
self.login = params[:user][:login] if params[:user][:login]
-
self.password = params[:user][:password]
-
self.password_confirmation = params[:user][:password_confirmation]
-
#self.openid_identifier = params[:user][:openid_identifier]
-
save
-
end
-
-
1
def signed_certificates
-
SignedCertificate.with_permissions_to(:update)
-
end
-
-
1
def referer_urls
-
visitor_tokens.map{|v|v.trackings.non_ssl_com_referer}.flatten.map{|t|t.referer.url}
-
end
-
-
1
def roles_humanize(target_account=nil)
-
Role.where(id: roles_for_account(target_account || ssl_account))
-
.map{|role| role.name.humanize(capitalize: false)}
-
end
-
-
1
def role_symbols(target_account=nil)
-
16
sa = target_account || ssl_account
-
16
return [] if sa.blank?
-
2
Rails.cache.fetch("#{cache_key}/role_symbols/#{sa.cache_key}") do
-
3
Role.where(id: roles_for_account(sa)).map{|role| role.name.underscore.to_sym}
-
end
-
end
-
1
memoize :role_symbols
-
-
1
def role_symbols_all_accounts
-
roles.map{|role| role.name.underscore.to_sym}
-
end
-
-
1
def certificate_order_by_ref(ref)
-
CertificateOrder.unscoped.includes(:certificate_contents).find(
-
Rails.cache.fetch("#{cache_key}/certificate_order_id/#{ref}") do
-
co=CertificateOrder.unscoped{(is_system_admins? ?
-
CertificateOrder : certificate_orders).find_by_ref(ref)}
-
co.id unless co.blank?
-
end)
-
end
-
-
# check for any SslAccount records do not have roles, users or an owner
-
# check for any User record that do not have a role for a given SslAccount
-
1
def self.integrity_check(fix=nil)
-
# find SslAccount records with no users
-
no_users=SslAccount.joins{ssl_account_users.outer}.where{ssl_account_users.ssl_account_id == nil}
-
# verify users do not exist
-
ap no_users.map(&:users).flatten.compact
-
no_users.delete if fix
-
# find User records with no ssl_accounts
-
no_ssl_accounts=User.unscoped.joins{ssl_account_users.outer}.where{ssl_account_users.user_id == nil}
-
ap no_ssl_accounts.map(&:ssl_accounts).flatten.compact
-
# find any SslAccount record without a role that belongs to a User
-
Assignment.joins{user}.joins{user.ssl_accounts}.where{ssl_account_id == nil}.count
-
# How many SslAccounts that do not have any role
-
SslAccount.joins{assignments.outer}.where{assignments.ssl_account_id==nil}.count
-
# How many SslAccounts that have the owner role
-
SslAccount.joins{assignments}.where{assignments.role_id==4}.count
-
end
-
-
1
def can_manage_certificates?
-
is_system_admins? && is_ra_admin?
-
end
-
-
1
def can_perform_accounting?
-
is_billing? || is_owner? || is_account_admin?
-
end
-
-
1
def is_admin?
-
9
role_symbols.include? Role::SYS_ADMIN.to_sym
-
end
-
-
1
def is_super_user?
-
9
role_symbols.include? Role::SUPER_USER.to_sym
-
end
-
-
1
def is_ra_admin?
-
role_symbols.include? Role::RA_ADMIN.to_sym
-
end
-
-
1
def is_owner?(target_account=nil)
-
# TODO need to separate out reseller from owner
-
1
role_symbols(target_account) & [Role::OWNER.to_sym,Role::RESELLER.to_sym]
-
end
-
-
1
def is_account_admin?
-
1
role_symbols.include? Role::ACCOUNT_ADMIN.to_sym
-
end
-
-
1
def is_standard?
-
(role_symbols & [Role::OWNER.to_sym, Role::ACCOUNT_ADMIN.to_sym]).any?
-
end
-
-
1
def is_reseller?(target_account=nil)
-
1
role_symbols(target_account).include? Role::RESELLER.to_sym
-
end
-
-
1
def is_billing?
-
1
role_symbols.include? Role::BILLING.to_sym
-
end
-
-
1
def is_billing_only?
-
role_symbols.include?(Role::BILLING.to_sym) && role_symbols.count == 1
-
end
-
-
1
def is_installer?
-
1
role_symbols.include? Role::INSTALLER.to_sym
-
end
-
-
1
def is_validations?
-
1
role_symbols.include? Role::VALIDATIONS.to_sym
-
end
-
-
1
def is_validations_only?
-
role_symbols.include?(Role::VALIDATIONS.to_sym) && role_symbols.count == 1
-
end
-
-
1
def is_validations_and_billing_only?
-
role_symbols.include?(Role::VALIDATIONS.to_sym) &&
-
role_symbols.include?(Role::BILLING.to_sym) &&
-
role_symbols.count == 2
-
end
-
-
1
def is_individual_certificate?
-
role_symbols.include? Role::INDIVIDUAL_CERTIFICATE.to_sym
-
end
-
-
1
def is_individual_certificate_only?
-
role_symbols==[Role::INDIVIDUAL_CERTIFICATE.to_sym]
-
end
-
-
1
def is_users_manager?
-
1
role_symbols.include? Role::USERS_MANAGER.to_sym
-
end
-
-
1
def is_affiliate?
-
ssl_account && !!ssl_account.affiliate
-
end
-
-
1
def is_system_admins?
-
8
is_super_user? || is_admin?
-
end
-
-
#if user has duplicate v2 users and is not consolidated
-
#then find the duplicate v2 user matching the username
-
#and copy it's username, crypted password, and email in the respective users fields
-
#and mark the user consolidated
-
1
def self.duplicate_logins(obj)
-
if obj.is_a? User
-
DuplicateV2User.where(:login=>obj.login)
-
else #assume string
-
DuplicateV2User.find_all_by_login(obj)
-
end
-
end
-
-
#TODO this is unfinished, going to instead email all
-
#duplicate_v2_users emails the corresponding consolidated username
-
1
def self.consolidate_login(obj, password)
-
user=duplicate_logins(obj).last.user
-
dupes=duplicate_logins(obj).last.user.duplicate_v2_users
-
matched=dupes.each do |dupe|
-
break dupe if (LegacySslMd5.matches? dupe.password, password)
-
end
-
if matched
-
user.login=obj
-
user.crypted_password=matched.password
-
end
-
end
-
-
#temporary function to assist in migration
-
1
if MIGRATING_FROM_LEGACY
-
def update_record_without_timestamping
-
class << self
-
def record_timestamps; false; end
-
end
-
-
save(false)
-
-
class << self
-
def record_timestamps; super ; end
-
end
-
end
-
end
-
-
1
def apply_omniauth(omniauth)
-
self.email = omniauth['user_info']['email']
-
-
# Update user info fetching from social network
-
case omniauth['provider']
-
when 'facebook'
-
# fetch extra user info from facebook
-
when 'twitter'
-
# fetch extra user info from twitter
-
end
-
end
-
-
1
def make_admin
-
unless roles.map(&:name).include?(Role::SYS_ADMIN)
-
roles << Role.find_by(name: Role::SYS_ADMIN)
-
assignments << Assignment.new(ssl_account_id: ssl_account.id, role_id: Role.find_by(name: Role::SYS_ADMIN).id)
-
end
-
end
-
-
1
def remove_admin
-
sysadmin_roles = get_roles_by_name(Role::SYS_ADMIN)
-
-
if sysadmin_roles.any?
-
sysadmin_roles.each do |r|
-
if r.ssl_account_id.nil?
-
r.delete
-
else
-
update_account_role(r.ssl_account_id, Role::SYS_ADMIN, Role::OWNER)
-
end
-
end
-
end
-
end
-
-
#
-
# User invite and approval token management
-
#
-
-
1
def pending_account_invites?
-
2
ssl_account_users.each do |ssl|
-
2
return true if approval_token_valid?(ssl_account_id: ssl.ssl_account_id, skip_match: true)
-
end
-
1
return false
-
end
-
-
1
def get_pending_accounts
-
1
acct_invite = []
-
1
ssl_account_users.each do |ssl|
-
1
params = {ssl_account_id: ssl.ssl_account_id, skip_match: true}
-
1
if approval_token_valid?(params)
-
1
acct_invite << {
-
acct_number: SslAccount.find_by_id(ssl.ssl_account_id).acct_number,
-
ssl_account_id: ssl.ssl_account_id,
-
approval_token: ssl.approval_token
-
}
-
end
-
end
-
1
acct_invite
-
end
-
-
1
def generate_approval_query(params)
-
ssl = get_ssl_acct_user_for_approval(params)
-
"?token=#{ssl.approval_token}&ssl_account_id=#{ssl.ssl_account_id}"
-
end
-
-
1
def get_approval_tokens
-
ssl_account_users.map(&:approval_token).uniq.compact.flatten
-
end
-
-
1
def approve_invite(params)
-
ssl_acct_id = params[:ssl_account_id]
-
errors = []
-
if user_approved_invite?(params)
-
errors << 'Invite already approved for this account!'
-
else
-
if approval_token_valid?(params)
-
set_approval_token(params.merge(clear: true))
-
ssl = approve_account(params)
-
if ssl
-
deliver_invite_to_account_accepted!(ssl.ssl_account)
-
Assignment.where( # notify team owner and users_manager(s)
-
ssl_account_id: ssl_acct_id,
-
role_id: Role.get_role_ids([Role::OWNER, Role::USERS_MANAGER])
-
).map(&:user).uniq.compact.each do |for_admin|
-
deliver_invite_to_account_accepted!(ssl.ssl_account, for_admin)
-
end
-
end
-
else
-
errors << 'Invite token is invalid or expired, please contact account admin!'
-
end
-
unless user_approved_invite?(params)
-
errors << 'Something went wrong! Please try again!'
-
end
-
end
-
errors
-
end
-
-
1
def decline_invite(params)
-
2
ssl = get_ssl_acct_user_for_approval(params)
-
2
if ssl
-
2
team = ssl.ssl_account
-
2
SystemAudit.create(
-
owner: self,
-
target: team,
-
action: 'Declined invitation to team (UsersController#decline_account_invite).',
-
notes: "User #{login} has declined invitation to team #{team.get_team_name} (##{team.acct_number})."
-
)
-
2
ssl.update(
-
approved: false,
-
token_expires: nil,
-
approval_token: nil,
-
declined_at: DateTime.now
-
)
-
end
-
end
-
-
1
def approve_all_accounts(log_invite=nil)
-
ssl_account_users.update_all(
-
approved: true, token_expires: nil, approval_token: nil
-
)
-
if log_invite
-
ssl_ids = assignments.where.not(role_id: Role.cannot_be_invited)
-
.map(&:ssl_account).uniq.compact.map(&:id)
-
ssl_account_users.where(ssl_account_id: ssl_ids).update_all(invited_at: DateTime.now)
-
end
-
end
-
-
1
def approval_token_not_expired?(params)
-
2
user_approved_invite?(params) || approval_token_valid?(params.merge(skip_match: true))
-
end
-
-
1
def approval_token_valid?(params)
-
9
ssl = get_ssl_acct_user_for_approval(params)
-
9
no_ssl_account = ssl.nil?
-
9
no_token_stored = ssl && ssl.approval_token.nil?
-
9
has_stored_token = ssl && ssl.approval_token
-
9
token_expired = has_stored_token && DateTime.parse(ssl.token_expires.to_s) <= DateTime.now
-
9
tokens_dont_match = params[:skip_match] ? false : (has_stored_token && ssl.approval_token != params[:token])
-
-
9
return false if no_ssl_account || no_token_stored || tokens_dont_match || token_expired
-
5
true
-
end
-
-
1
def get_all_approved_accounts
-
6
(self.is_system_admins? ? SslAccount.unscoped : self.approved_ssl_accounts).order("created_at desc")
-
end
-
-
1
def get_all_approved_teams
-
(self.is_system_admins? ? SslAccount.unscoped : self.approved_teams).order("created_at desc")
-
end
-
-
1
def user_approved_invite?(params)
-
3
ssl = get_ssl_acct_user_for_approval(params)
-
3
ssl && ssl.approved && ssl.token_expires.nil? && ssl.approval_token.nil?
-
end
-
-
1
def user_declined_invite?(params)
-
2
ssl = get_ssl_acct_user_for_approval(params)
-
2
ssl && !ssl.approved && ssl.token_expires.nil? && ssl.approval_token.nil?
-
end
-
-
1
def resend_invitation_with_token(params)
-
errors = []
-
invite_existing_user(params)
-
unless approval_token_valid?(params.merge(skip_match: true))
-
errors << 'Token was not renewed. Please try again'
-
end
-
errors
-
end
-
-
1
def set_approval_token(params)
-
14
ssl = get_ssl_acct_user_for_approval(params)
-
14
if ssl
-
14
ssl.update(
-
approved: false,
-
14
token_expires: (params[:clear] ? nil : (DateTime.now + 72.hours)),
-
14
approval_token: (params[:clear] ? nil : generate_approval_token),
-
invited_at: DateTime.now,
-
declined_at: nil
-
)
-
end
-
end
-
-
1
def set_status_for_account(status_type, target_ssl=nil)
-
ssl = target_ssl.nil? ? ssl_account : target_ssl
-
owner_id = Role.get_owner_id
-
-
target_ssl = if roles_for_account(ssl).include?(owner_id)
-
# if owner, disable access to this ssl account for all associated users
-
SslAccountUser.where(ssl_account_id: ssl.id)
-
else
-
ssl_account_users.where(ssl_account_id: ssl.id)
-
end
-
target_ssl.update_all(user_enabled: (status_type == :enabled))
-
clear_def_ssl_for_users(target_ssl)
-
end
-
-
1
def set_status_all_accounts(status_type)
-
ssl_accounts.each{|target_ssl| set_status_for_account(status_type, target_ssl)} if status_type
-
end
-
-
1
def clear_def_ssl_for_users(target_ssl_account_users)
-
# if any user in target_ssl_account_users has their default_ssl_account set
-
# to ssl_account in target_ssl_account_users, clear user's default_ssl_account
-
# since it's disabled
-
users_clear_ssl = target_ssl_account_users.map(&:user).uniq.flatten.compact
-
.keep_if{|u| target_ssl_account_users.map(&:ssl_account_id)
-
.include?(u.default_ssl_account)}.map(&:id)
-
User.where(id: users_clear_ssl).update_all(default_ssl_account: nil) if users_clear_ssl.any?
-
end
-
-
1
private
-
-
# https://github.com/binarylogic/authlogic/issues/81
-
1
def should_record_timestamps?
-
116
changed_keys = self.changes.keys - ["last_request_at", "perishable_token", "updated_at", "created_at"]
-
116
changed_keys.present? && super
-
end
-
-
# https://github.com/binarylogic/authlogic/issues/485
-
1
def should_reset_perishable_token
-
214
if changed? && changed_attributes.keys != ['last_request_at']
-
214
reset_perishable_token
-
end
-
end
-
-
1
def self_or_other(user_id)
-
5
user = user_id ? User.find_by_id(user_id) : self
-
end
-
-
1
def approve_account(params)
-
92
ssl = get_ssl_acct_user_for_approval(params)
-
92
ssl.update(approved: true, token_expires: nil, approval_token: nil) if ssl
-
92
ssl
-
end
-
-
1
def generate_approval_token
-
14
OAuth::Helper.generate_key(40)[0,40]
-
end
-
-
1
def get_ssl_acct_user_for_approval(params)
-
122
SslAccountUser.where(
-
122
user_id: (params[:id].nil? ? id : params[:id]),
-
ssl_account_id: params[:ssl_account_id]
-
).first
-
end
-
-
1
def get_first_approved_acct
-
sa_id=Rails.cache.fetch("#{cache_key}/get_first_approved_acct") do
-
ssl = ssl_account_users.where(approved: true, user_enabled: true)
-
ssl.any? ? ssl.first.ssl_account_id : nil
-
end
-
ssl_accounts.find_by_id(sa_id) if sa_id
-
end
-
-
1
def self.change_login(old, new)
-
#requires SQL statement to change login
-
User.where('login LIKE ?', old).update_all(login: new)
-
end
-
-
1
def validate_password?
-
108
(!new_record? || (new_record? && crypted_password)) && require_password?
-
end
-
end
-
class UserGroup < ActiveRecord::Base
-
belongs_to :ssl_account
-
has_and_belongs_to_many :users
-
easy_roles :roles
-
end
-
class UserNotifier < ActionMailer::Base
-
helper :application
-
include ActionView::Helpers::TextHelper
-
include ActionView::Helpers::SanitizeHelper
-
extend ActionView::Helpers::SanitizeHelper::ClassMethods
-
# default_url_options[:host] = Settings.actionmailer_host
-
-
def activation_instructions(user)
-
@account_activation_url = register_url(user.perishable_token)
-
mail subject: "SSL.com user account activation instructions",
-
from: Settings.from_email.activations,
-
to: user.email
-
end
-
-
def activation_confirmation(user)
-
@account_url = account_url
-
@login = user.login
-
mail subject: "SSL.com user account activated",
-
from: Settings.from_email.activations,
-
to: user.email
-
end
-
-
def auto_activation_confirmation(user)
-
@account_url = account_url
-
@login = user.login
-
mail subject: "SSL.com user account auto activated",
-
from: Settings.from_email.activations,
-
to: user.email
-
end
-
-
def password_reset_instructions(user)
-
@edit_password_reset_url = edit_password_reset_url(user.perishable_token)
-
mail subject: "SSL.com user account password reset instructions",
-
from: Settings.from_email.activations,
-
to: user.email
-
end
-
-
def password_changed(user)
-
mail subject: "SSL.com user account password changed",
-
from: Settings.from_email.activations,
-
to: user.email
-
end
-
-
def email_changed(user, email)
-
@user=user
-
mail subject: "SSL.com user account email address changed",
-
from: Settings.from_email.activations,
-
to: email
-
end
-
-
def username_reminder(user)
-
@login = user.login
-
mail subject: "SSL.com username reminder",
-
from: Settings.from_email.activations,
-
to: user.email
-
end
-
-
def activation_confirmation_by_sysadmin(user, password)
-
@account_url = account_url
-
@login = user.login
-
@password = password
-
-
mail subject: "SSL.com user account activated by system admin",
-
from: Settings.from_email.activations,
-
to: user.email
-
end
-
-
def signup_invitation(user, current_user, base_url, invited_teams)
-
@user = user
-
@current_user = current_user
-
@ssl_account = user.ssl_account
-
@invited_teams = invited_teams
-
@invite_url = "#{base_url}register/#{@user.perishable_token}?invite=true"
-
@login = user.login
-
mail subject: "#{@current_user.login} has invited you to join SSL.com",
-
from: Settings.from_email.activations,
-
to: user.email
-
end
-
-
def invite_to_account(invite_user, current_user, ssl_account_id)
-
@invited_user = invite_user
-
@current_user = current_user.is_a?(User) ? current_user : User.find(current_user)
-
@ssl_account = SslAccount.find ssl_account_id
-
@approval_url = approve_account_invite_user_url(@invited_user)
-
@approval_url << @invited_user.generate_approval_query(ssl_account_id: @ssl_account.id)
-
@token_expire = @invited_user.ssl_account_users.find_by(ssl_account_id: @ssl_account.id).token_expires
-
mail subject: "Invition to SSL.com team #{@ssl_account.get_team_name}",
-
from: Settings.from_email.activations,
-
to: @invited_user.email
-
end
-
-
def invite_to_account_notify_admin(invite_user, current_user, ssl_account_id)
-
@invited_user = invite_user
-
@current_user = current_user.is_a?(User) ? current_user : User.find(current_user)
-
@ssl_account = SslAccount.find ssl_account_id
-
mail subject: "You have invited a user to your SSL.com team #{@ssl_account.get_team_name}",
-
from: Settings.from_email.activations,
-
to: @current_user.email
-
end
-
-
def invite_to_account_accepted(invite_user, ssl_account, for_admin)
-
@invited_user = invite_user
-
@ssl_account = ssl_account
-
@admin = for_admin
-
subject = if @admin
-
"Invition to SSL.com team #{@ssl_account.get_team_name} was accepted by user #{@invited_user.login}."
-
else
-
"You have accepted SSL.com invitation to team #{@ssl_account.get_team_name}."
-
end
-
mail subject: subject,
-
from: Settings.from_email.activations,
-
to: (@admin ? @admin.email : @invited_user.email)
-
end
-
-
def invite_to_account_disabled(disabled_user, account, current_user)
-
@disabled_user = disabled_user
-
@current_user = current_user
-
@team = account
-
mail subject: "A disabled user #{@disabled_user.login} was invited to team #{@team.get_team_name}",
-
from: Settings.support_email,
-
to: Settings.support_email
-
end
-
-
def removed_from_account(user, account, current_user)
-
@remove_user = user
-
@current_user = current_user
-
@ssl_account = account
-
mail subject: "You have been removed from SSL.com account",
-
from: Settings.from_email.activations,
-
to: @remove_user.email
-
end
-
-
def removed_from_account_notify_admin(user, account, current_user)
-
@remove_user = user
-
@current_user = current_user
-
@ssl_account = account
-
mail subject: "You have removed user from SSL.com account",
-
from: Settings.from_email.activations,
-
to: @current_user.email
-
end
-
-
def leave_team(current_user, account)
-
@current_user = current_user
-
@team = account
-
@owner_user = @team.get_account_owner
-
mail subject: "You have left SSL.com team #{@team.get_team_name}",
-
from: Settings.from_email.activations,
-
to: @current_user.email
-
end
-
-
def leave_team_notify_admins(remove_user, notify_user, account)
-
@remove_user = remove_user
-
@notify_user = notify_user
-
@team = account
-
mail subject: "User #{@remove_user.login} has left your SSL.com team #{@team.get_team_name}",
-
from: Settings.from_email.activations,
-
to: @notify_user.email
-
end
-
-
def ssl_cert_private_key(user, resource_id, host_name, custom_domain_id)
-
@user = user
-
@user_name = [@user.first_name, @user.last_name].join(" ")
-
@resource_id = resource_id
-
@host_name = host_name
-
@custom_domain_id = custom_domain_id
-
mail subject: "Request for updating certificates of custom domain #{@host_name} for User #{@user.email}",
-
from: Settings.from_email.activations,
-
to: "mamalos@ssl.com"
-
end
-
-
def generate_install_ssl(user, resource_id, host_name, to_address)
-
@user = user
-
@user_name = [@user.first_name, @user.last_name].join(" ")
-
@resource_id = resource_id
-
@host_name = host_name
-
mail subject: "Processing SSL Certificate Request",
-
from: Settings.from_email.activations,
-
to: to_address
-
end
-
-
def auto_register_ssl_manager_to_team(user, ssl_account)
-
mail subject: "Auto Registered SSL Manager to SSL.com team #{ssl_account.get_team_name}",
-
from: Settings.from_email.activations,
-
to: user.email
-
end
-
-
def register_ssl_manager_to_team(user, ref, ssl_account)
-
base_path = "https://" + Settings.community_domain
-
@approval_url = base_path + approve_ssl_manager_path(ref)
-
-
mail subject: "Register SSL Manager to SSL.com team #{ssl_account.get_team_name}",
-
from: Settings.from_email.activations,
-
to: user.email
-
end
-
-
protected
-
def setup_email(user)
-
@recipients = "#{user.email}"
-
setup_sender_info
-
@subject = "[#{Settings.community_name}] "
-
@sent_on = Time.now
-
@body[:user] = user
-
end
-
-
def setup_sender_info
-
@from = "The #{Settings.community_name} Team <#{Settings.support_email}>"
-
headers "Reply-to" => "#{Settings.support_email}"
-
@content_type = "text/plain"
-
end
-
-
end
-
1
class UserSession < Authlogic::Session::Base
-
1
SESSION_KEY="_ssl_com_session_10242016"
-
1
logout_on_timeout true
-
# consecutive_failed_logins_limit 1
-
-
1
after_create do |this_session|
-
70
user = this_session.record
-
SystemAudit.create(
-
owner: user,
-
target: nil,
-
action: "User #{user.login} has logged in from ip address #{user.current_login_ip}",
-
notes: "#{User.get_user_accounts_roles_names(user).to_s}"
-
70
) if user.active? && !user.is_disabled?
-
end
-
-
1
before_validation do |this_session|
-
124
if User.find_by_login(this_session.login).try("is_system_admins?".to_sym)
-
UserSession.consecutive_failed_logins_limit 5
-
else
-
124
UserSession.consecutive_failed_logins_limit 15
-
end
-
end
-
-
1
before_destroy do |this_session|
-
user = this_session.record
-
SystemAudit.create(
-
owner: user,
-
target: nil,
-
action: "User #{user.login} has logged out from ip address #{user.current_login_ip}",
-
notes: "#{User.get_user_accounts_roles_names(user).to_s}"
-
) if user.active? && !user.is_disabled?
-
end
-
end
-
class V2MigrationProgress < ActiveRecord::Base
-
belongs_to :migratable, :polymorphic=>true
-
validates_uniqueness_of :source_id, :scope=>:source_table_name
-
-
def self.find_by_source(obj)
-
find_by_old_object(obj)
-
end
-
-
#Finds the legacy object based on the transitory object
-
def self.find_by_old_object(obj)
-
pk=obj.class.primary_key
-
self.find_by_source_table_name_and_source_id(obj.class.table_name,
-
obj.send(pk))
-
end
-
-
def self.find_non_mapped(klass)
-
joins("RIGHT JOIN `#{klass.table_name}` ON `#{klass.table_name}`.`id` =
-
`v2_migration_progresses`.`migratable_id` AND `v2_migration_progresses`.`migratable_type` = '#{klass}'").where{migratable_id==nil}
-
# klass.where{id.not_in(mapped.select{migratable_id})}
-
end
-
-
def self.find_multiple_mapped(klass)
-
joins("INNER JOIN `#{klass.table_name}` ON `#{klass.table_name}`.`id` =
-
`v2_migration_progresses`.`migratable_id` AND `v2_migration_progresses`.`migratable_type` = '#{klass}'").
-
group(:migratable_id).having("count(migratable_id)>1")
-
end
-
-
def self.find_by_migratable(migratable, which=:first)
-
where(:migratable_type=>migratable.class.to_s, :migratable_id=>migratable.id)
-
end
-
-
def self.find_by_migratable_and_source_table_name(
-
migratable, source_table_name, which=:first)
-
find(which) do |v|
-
v.migratable_type==migratable.class.to_s &&
-
v.migratable_id==migratable.id &&
-
v.source_table_name==source_table_name
-
end
-
end
-
-
def self.remove_legacy_orphans(legacy)
-
#l_ids=all_ids legacy
-
#vs_ids=select(:source_id).where(:source_table_name.eq => legacy.table_name).map(&:source_id)
-
#if vs_ids.count > l_ids.count
-
# diff = vs_ids - l_ids
-
# where(:source_id + diff).delete_all
-
#else
-
# 0
-
#end
-
options={class: legacy, class_name: legacy.table_name, id: :source_id}
-
remove_orphans options
-
end
-
-
def self.remove_migratable_orphans
-
types = all.map(&:migratable_type).uniq.compact
-
types.each do |type|
-
klass=type.constantize
-
options={class: klass, class_name: type, id: :migratable_id}
-
remove_orphans options
-
end
-
end
-
-
def self.remove_orphans(options)
-
t_ids=all_ids options[:class]
-
vs_ids=select(options[:id]).where{migratable_type == options[:class_name]}.map(&options[:id])
-
diff = vs_ids - t_ids
-
removed=unless diff.empty?
-
where{options[:id] >> diff}.delete_all
-
else
-
0
-
end
-
ap "removed #{removed} orphaned records for #{options[:class_name]}"
-
end
-
-
def self.status(obj)
-
unmigrated = V2MigrationProgress.select(:source_id).where(
-
:source_table_name =~ obj.table_name, :migrated_at.eq=>nil).map(&:source_id)
-
p unmigrated.empty? ? "successfully migrated #{obj.base_class.to_s}" :
-
"the following #{unmigrated.count} #{obj.base_class.to_s} failed migration:
-
#{unmigrated.join(', ')}"
-
end
-
-
def self.all_ids(klass)
-
klass.select(klass.primary_key.to_sym).map(&("#{klass.primary_key}".to_sym))
-
end
-
-
def self.migratable_types
-
all.map(&:migratable_type).uniq
-
end
-
-
def source_obj
-
o=OldSite::Base.descendants.find{|c|
-
c.table_name==source_table_name}
-
eval "#{o.name}.find_by_#{o.primary_key}(source_id)"
-
end
-
end
-
class Validation < ActiveRecord::Base
-
has_many :certificate_orders, -> { unscope(where: [:workflow_state, :is_expired]) }
-
has_many :ssl_accounts, through: :certificate_orders
-
has_many :users, through: :ssl_accounts
-
has_many :validation_rulings, :as=>:validation_rulable
-
has_many :validation_rules, :through => :validation_rulings
-
has_many :validation_history_validations
-
has_many :validation_histories, :through=>
-
:validation_history_validations, :after_add=>:modify_validation_rulings do
-
def applied_to(validation_rule)
-
all.find_all{|vh|vh.validation_rules.include? validation_rule}
-
end
-
end
-
-
include Workflow
-
workflow do
-
state :new do
-
event :validation_submitted, :transitions_to => :pending
-
event :approve_through_override, :transitions_to =>
-
:approved_through_override
-
event :approve, transitions_to: :approved
-
end
-
-
state :pending do
-
event :approve, :transitions_to => :approved
-
event :unapprove, :transitions_to => :unapproved
-
end
-
-
state :approved do
-
event :unapprove, :transitions_to => :unapproved
-
event :validation_submitted, :transitions_to => :pending
-
event :pend, :transitions_to => :pending
-
-
on_entry do
-
self.validation_rulings.each {|v|v.approve! unless v.approved?}
-
end
-
end
-
-
state :approved_through_override do
-
event :unapprove, :transitions_to => :unapproved
-
-
on_entry do
-
self.validation_rulings.each {|v|v.approve! unless v.approved?}
-
end
-
end
-
-
state :unapproved do
-
event :approve, :transitions_to => :approved
-
event :validation_submitted, :transitions_to => :pending
-
end
-
-
state :not_applicable
-
end
-
-
NONE_SELECTED="None"
-
COMODO_EMAIL_LOOKUP_THRESHHOLD=20 #the number of domains before we switch to manually generating validation addresses to reduce latency
-
-
def last_document_uploaded_on
-
return "" if validation_histories.empty?
-
validation_histories.last.created_at.strftime("%b %d, %Y")
-
end
-
-
def modify_validation_rulings(validation_history)
-
validation_rulings.each{|vr| vr.validation_submitted! if vr.new?}
-
end
-
end
-
class ValidationCompliance < ActiveRecord::Base
-
end
-
class ValidationContact < CertificateContact
-
end
-
# The validation document
-
-
class ValidationHistory < ActiveRecord::Base
-
has_many :validation_ruling_validation_histories
-
has_many :validation_rulings, :through=>:validation_ruling_validation_histories, :as=>:validation_rulable
-
has_many :validation_rules, :through => :validation_rulings
-
has_many :validation_history_validations
-
has_many :validations, :through=>:validation_history_validations
-
has_many :certificate_orders, through: :validations
-
attr_protected :publish_to_site_seal_approval
-
attr_protected :validation_rules
-
serialize :satisfies_validation_methods
-
has_attached_file :document, :url => "/:class/:id/:attachment/:style.:extension",
-
# => Use this if we want to store to the file system instead of s3.
-
# Comment out the remainder parameters
-
# :path => ":Rails.root/attachments/:class/:id/:attachment/:style.:extension",
-
# :styles=>{:thumb=>['100x100#', :png], :preview=>['400x400#', :png]}
-
# styles: {:thumb=>['100x100#', :png], :preview=>['400x400#', :png]},
-
styles: lambda { |a|
-
a.instance.is_image? ? {:thumb=>['100x100#', :png], :preview=>['400x400#', :png]} : {}
-
},
-
s3_permissions: :private,
-
s3_protocol: 'http',
-
path: ":id_partition/:random_secret/:style.:extension"
-
-
# has_attached_file :document, :url => "/public/images/validations/:class/:id/:attachment/:style.:extension",
-
# styles: lambda { |a|
-
# a.instance.is_image? ? {:thumb=>['100x100#', :png], :preview=>['400x400#', :png]} : {}
-
# }
-
-
CONTENT_TYPES = [['image/jpeg', 'jpg, jpeg, jpe, jfif'], ['image/png','png'],
-
['application/pdf', 'pdf'], ['image/tiff', 'tif, tiff'],
-
['image/gif', 'gif'], ['image/bmp', 'bmp'],
-
['application/zip', 'zip'], ['application/vnd.oasis.opendocument.text', 'odt'],
-
['application/msword', 'doc'], ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'docx'],
-
['audio/mpeg', 'mp3'], ['audio/x-mpeg', 'mp3'], ['audio/mp3', 'mp3'], ['audio/x-mp3', 'mp3'], ['audio/mpeg3', 'mp3'],
-
['audio/x-mpeg3', 'mp3'], ['audio/mpg', 'mp3'], ['audio/x-mpg', 'mp3'], ['audio/x-mpegaudio', 'mp3'], ['text/plain', 'txt, text']]
-
-
validates_attachment_content_type :document, :content_type => ValidationHistory::CONTENT_TYPES.transpose[0]
-
-
preference :viewing_method, :string, :default=>"download" #or thumbnail
-
-
default_scope{ where{id << [3126]}} # temporary https://secure.ssl.com/certificate_orders/co-141e6s5s9/validation/edit
-
-
# interpolate in paperclip
-
Paperclip.interpolates :random_secret do |attachment, style|
-
attachment.instance.random_secret
-
end
-
-
def is_image?
-
document.content_type =~ %r(image)
-
end
-
-
def registrant_document_url(registrant, style=nil)
-
if style.blank? || document_content_type =~ %r(audio)
-
%{/#{self.class.name.tableize}/#{id}/documents/#{document_file_name}?registrant=#{registrant.id}}
-
else
-
%{/#{self.class.name.tableize}/#{id}/documents/#{document.styles[style].name}.#{document.styles[style].format}?registrant=#{registrant.id}}
-
end
-
end
-
-
def document_url(style=nil)
-
if style.blank? || document_content_type =~ %r(audio)
-
%{/#{self.class.name.tableize}/#{id}/documents/#{document_file_name}}
-
else
-
%{/#{self.class.name.tableize}/#{id}/documents/#{document.styles[style].name}.#{document.styles[style].format}}
-
end
-
end
-
-
#def authenticated_s3_get_url(options={})
-
# options.reverse_merge! :expires_in => 10.minutes, :use_ssl => false
-
# AWS::S3::S3Object.url_for document.path(options[:style]), document.options[:bucket], options
-
#end
-
-
def self.multi_upload_types
-
ValidationHistory::CONTENT_TYPES.transpose[1].map{|ct|ct.split(',')}.
-
flatten.join('|').gsub(' ', '')
-
end
-
-
def self.acceptable_file_types
-
ValidationHistory::CONTENT_TYPES.transpose[1].map{|ct|ct.split(',')}.
-
flatten.join(', ').gsub(' ', ' ')
-
end
-
-
def random_secret
-
if @new_record
-
set_random_secret
-
end
-
read_attribute(:random_secret)
-
end
-
-
def can_publish_to_site_seal?
-
(publish_to_site_seal && publish_to_site_seal_approval)
-
end
-
-
def authenticated_s3_get_url(options={})
-
expires_in = 10.minutes
-
options.reverse_merge! expires_in: expires_in, use_ssl: true
-
document.s3_object(options[:style]).presigned_url(:get, secure: true, expires_in: expires_in).to_s
-
end
-
-
private
-
-
def set_random_secret
-
self.random_secret = SecureRandom.hex(8)
-
end
-
end
-
class ValidationHistoryValidation < ActiveRecord::Base
-
belongs_to :validation_history
-
belongs_to :validation
-
-
validates_uniqueness_of :validation_id, :scope=>[:validation_history_id]
-
end
-
# The actual validation rule or requirement
-
-
class ValidationRule < ActiveRecord::Base
-
belongs_to :parent, :foreign_key => :parent_id
-
serialize :applicable_validation_methods
-
serialize :required_validation_methods
-
has_many :validation_rulings
-
has_many :certificates, :through=>:validation_rulings,
-
:source=>:validation_rulable, :source_type=>"Certificate"
-
has_many :validations, :through=>:validation_rulings,
-
:source=>:validation_rulable, :source_type=>"Validation"
-
-
#validation types
-
EV = %w(ev validation)
-
ORGANIZATION = %w(organization validation)
-
DOMAIN = %w(domain validation)
-
-
# description
-
LEGAL_EXISTENCE="verify legal existence"
-
PHYSICAL_EXISTENCE="verify physical/operational existence"
-
-
#methods
-
DUNS = %w(duns\ and\ bradstreet\ (hoovers))
-
EV_AUTHORIZATION_FORM = %w(ev\ authorization\ form)
-
EV_SUBSCRIBER_AGREEMENT = %w(ev\ subscriber\ agreement)
-
SUBSCRIBER_AGREEMENT = %w(subscriber\ agreement)
-
CERTIFICATE_REQUEST_FORM = %w(certificate\ request\ form)
-
AUTOMATIC_DOMAIN_LOOKUP = %w(automatic\ domain\ lookup)
-
MANUAL_DOMAIN_LOOKUP = %w(manual\ domain\ lookup)
-
ARTICLES_OF_INCORPORATION = %w(articles\ of\ incorporation)
-
CERTIFICATE_OF_FORMATION = %w(certificate\ of\ formation)
-
CHARTER_DOCUMENTS = %w(charter\ documents)
-
BUSINESS_LICENSE = %w(business\ license)
-
DBA = %w(doing\ business\ as)
-
REGISTRATION_OF_TRADE_NAME = %w(registration\ of\ trade\ name)
-
PARTNERSHIP_PAPERS = %w(partnership\ papers)
-
FICTITIOUS_NAME_STATEMENT = %w(fictitious\ name\ statement)
-
LICENSE = %w(vendor/reseller/merchant\ license)
-
MERCHANT_CERTIFICATE = %w(merchant\ certificate)
-
ORG_VALIDATION_METHODS = ARTICLES_OF_INCORPORATION +
-
CERTIFICATE_OF_FORMATION + CHARTER_DOCUMENTS + BUSINESS_LICENSE +
-
DBA + REGISTRATION_OF_TRADE_NAME + PARTNERSHIP_PAPERS +
-
FICTITIOUS_NAME_STATEMENT + LICENSE +
-
MERCHANT_CERTIFICATE + DUNS
-
-
default_scope{ order("description asc")}
-
-
def self.add_ev_rules
-
ValidationRule.create description: "ev agreement and request form",
-
applicable_validation_methods: EV_SUBSCRIBER_AGREEMENT+EV_AUTHORIZATION_FORM,
-
required_validation_methods: EV_SUBSCRIBER_AGREEMENT+EV_AUTHORIZATION_FORM,
-
required_validation_methods_operator: "AND"
-
ValidationRule.create description: LEGAL_EXISTENCE,
-
applicable_validation_methods: ORG_VALIDATION_METHODS
-
ValidationRule.create description: PHYSICAL_EXISTENCE,
-
applicable_validation_methods: ORG_VALIDATION_METHODS
-
end
-
-
end
-
# The decision or current status on a validation rule requirement on a given validation material (document)
-
-
class ValidationRuling < ActiveRecord::Base
-
belongs_to :validation_rulable, :polymorphic=>true
-
belongs_to :validation_rule
-
acts_as_notable
-
-
validates_uniqueness_of :validation_rule_id, :scope=>[:validation_rulable_id,
-
:validation_rulable_type]
-
-
REVIEWING = "reviewing documents"
-
WAITING_FOR_DOCS = "waiting for documents"
-
INSUFFICIENT = "insufficient, more documents needed"
-
APPROVED = "approved"
-
UNAPPROVED = "unapproved"
-
-
#admin actions
-
UNAPPROVE='unapprove'
-
APPROVE='approve'
-
MORE_REQUIRED='more required'
-
DECLINED_ACTIONS=[UNAPPROVE, MORE_REQUIRED]
-
-
APPROVED_CLASS='validation_approved'
-
WAITING_CLASS='validation_waiting'
-
ATTENTION_CLASS='validation_attention'
-
-
NEW_STATUS = "processing"
-
NEW_EV_STATUS = "validation documents required"
-
MORE_REQUIRED_STATUS = "additional documentation needed"
-
PENDING_STATUS = "performing validations"
-
PENDING_EXPRESS_STATUS = "reviewing organization validation"
-
APPROVED_STATUS = "validation has been satisfied"
-
UNAPPROVED_STATUS = "validation documents have been uploaded but did not meet minimum requirements"
-
-
DCV_WAIT_STATUS = "waiting on domain control response"
-
-
EXPAND=". click for details"
-
-
include Workflow
-
workflow do
-
state :new do
-
event :unapprove, :transitions_to => :unapproved
-
event :approve, :transitions_to => :approved
-
event :require_more, :transitions_to => :more_required
-
event :validation_submitted, :transitions_to => :pending
-
event :approve_through_override, :transitions_to => :approved_through_override
-
end
-
-
state :pending do
-
event :approve, :transitions_to => :approved
-
event :unapprove, :transitions_to => :unapproved
-
event :require_more, :transitions_to => :more_required
-
-
on_entry do
-
vr=self.validation_rulable
-
if vr.is_a?(Validation) && vr.approved?
-
vr.pend!
-
end
-
end
-
end
-
-
state :approved do
-
event :unapprove, :transitions_to => :unapproved
-
event :validation_submitted, :transitions_to => :pending
-
event :require_more, :transitions_to => :more_required
-
event :pend, :transitions_to => :pending
-
-
on_entry do
-
vr=self.validation_rulable
-
if vr.is_a?(Validation) && !vr.approved? && vr.validation_rulings.all{|v|v.approved?}
-
vr.approve!
-
end
-
end
-
end
-
-
state :approved_through_override do
-
event :unapprove, :transitions_to => :unapproved
-
-
on_entry do
-
vr=self.validation_rulable
-
if vr.is_a?(Validation) && !vr.approved? && vr.validation_rulings.all{|v|v.approved?}
-
vr.approve!
-
end
-
end
-
end
-
-
state :more_required do
-
event :approve, :transitions_to => :approved
-
event :unapprove, :transitions_to => :unapproved
-
event :pend, :transitions_to => :pending
-
end
-
-
state :unapproved do
-
event :approve, :transitions_to => :approved
-
event :validation_submitted, :transitions_to => :pending
-
event :require_more, :transitions_to => :more_required
-
event :pend, :transitions_to => :pending
-
end
-
-
state :not_applicable do
-
-
end
-
-
state :certificate do
-
-
end
-
end
-
end
-
class ValidationRulingValidationHistory < ActiveRecord::Base
-
self.table_name="validation_rulings_validation_histories"
-
belongs_to :validation_ruling
-
belongs_to :validation_history
-
end
-
class VisitorToken < ActiveRecord::Base
-
validates_presence_of :guid
-
-
belongs_to :user
-
belongs_to :affiliate
-
has_many :trackings
-
has_many :tracked_urls, :through=>:trackings
-
has_many :orders
-
-
GUID = :guid
-
end
-
# This allows a reseller to white-label the RA portal. It allows for optional seperate db
-
1
class Website < ActiveRecord::Base
-
1
belongs_to :db
-
-
1
def self.domain_contraints
-
1
Rails.cache.fetch("domain_contraints",expires_in: 24.hours){Website.pluck(:api_host)+Sandbox.pluck(:host)}
-
end
-
-
1
def self.current_site(domain)
-
cs_id=Rails.cache.fetch("current_site/#{domain}",
-
expires_in: 24.hours) {
-
cs=self.where{(host == domain) | (api_host == domain)}.last
-
cs ? cs.id : ''}
-
Website.find cs_id unless cs_id.blank?
-
end
-
-
1
def use_database
-
ActiveRecord::Base.establish_connection(website_connection)
-
CertificateContent.cli_domain=self.api_host unless self.api_host.blank?
-
end
-
-
# Revert back to the shared database
-
1
def self.revert_database
-
ActiveRecord::Base.establish_connection(Website::default_connection)
-
end
-
-
# production api
-
1
def api_domain
-
Rails.cache.fetch("api_domain/#{cache_key}") {api_host}
-
end
-
-
# production test api
-
1
def test_api_domain
-
Rails.cache.fetch("test_api_domain/#{cache_key}") {api_host}
-
end
-
-
# development api
-
1
def dev_api_domain
-
Rails.cache.fetch("dev_api_domain/#{cache_key}") {api_host}
-
end
-
-
#development text api
-
1
def dev_test_api_domain
-
Rails.cache.fetch("dev_test_api_domain/#{cache_key}") {api_host}
-
end
-
-
1
private
-
-
# Regular database.yml configuration hash
-
1
def self.default_connection
-
@default_config ||= ActiveRecord::Base.connection.instance_variable_get("@config").dup
-
end
-
-
# Return regular connection hash but with database name changed
-
# The database name is a attribute (column in the database)
-
1
def website_connection
-
Website::default_connection.dup.update(database: self.db.name)
-
end
-
end
-
class Whitelist < Blocklist
-
end
-
class WhoisLookup < ActiveRecord::Base
-
belongs_to :csr
-
before_create :query_whois
-
-
WHOIS=->(domain){%x"whois #{domain}"}
-
-
def query_whois
-
if csr.top_level_domain && Whois.find(csr.top_level_domain).try(:valid?)
-
self.raw = whois = Whois.find(csr.top_level_domain)
-
unless whois.blank?
-
self.expiration = whois.expiration if whois.expiration_date_known?
-
self.record_created_on = whois.creation_date if whois.creation_date_known?
-
self.status = whois.status
-
end
-
end
-
end
-
-
def email_addresses
-
self.raw.scan(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/im).uniq unless
-
self.raw.blank?
-
end
-
-
def self.email_addresses(raw)
-
raw.scan(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/im).uniq unless
-
raw.blank?
-
end
-
-
def self.use_gem(fqdn)
-
d=::PublicSuffix.parse(fqdn)
-
Whois.whois(ActionDispatch::Http::URL.extract_domain(d.domain, 1)).inspect
-
end
-
end
-
class Api::V1::ApiCertificateCreate_v1_4Serializer < Api::V1::BaseSerializer
-
-
attribute :ref
-
attribute :registrant
-
attribute :order_status
-
attribute :validations
-
attribute :order_amount
-
attribute :certificate_url
-
attribute :receipt_url
-
attribute :smart_seal_url
-
attribute :validation_url
-
attribute :api_request
-
attribute :api_response
-
attribute :debug
-
attribute :external_order_number
-
attribute :certificates
-
-
def attributes
-
attrs = super
-
if object.debug.nil?
-
attrs = attrs.delete_if {|key, value| %w{api_request api_response debug}.include?(key)}
-
end
-
attrs
-
end
-
end
-
class Api::V1::ApiCertificateRetrieveSerializer < Api::V1::BaseSerializer
-
attribute :ref
-
attribute :description
-
attribute :order_status
-
attribute :order_date
-
attribute :expiration_date
-
attribute :domains
-
attribute :common_name
-
attribute :product_type
-
attribute :period
-
end
-
class Api::V1::BaseSerializer
-
include JSONAPI::Serializer
-
-
def type
-
object.class.name.demodulize.singularize
-
end
-
-
def format_name(attribute_name)
-
attribute_name.to_s
-
end
-
-
def relationship_self_link(attribute_name); end
-
-
def relationship_related_link(attribute_name); end
-
-
def self_link; end
-
end
-
class Api::V1:: BillingProfileSerializer < Api::V1::BaseSerializer
-
attribute :first_name
-
attribute :last_name
-
attribute :credit_card
-
attribute :last_digits
-
attribute :expiration_year
-
attribute :expiration_month
-
end
-
class Api::V1::CertificateContactSerializer < Api::V1::BaseSerializer
-
attribute :title
-
attribute :first_name
-
attribute :last_name
-
attribute :company_name
-
attribute :department
-
attribute :po_box
-
attribute :address1
-
attribute :address2
-
attribute :address3
-
attribute :city
-
attribute :state
-
attribute :country
-
attribute :postal_code
-
attribute :email
-
attribute :phone
-
attribute :ext
-
attribute :fax
-
end
-
class Api::V1::RegistrantSerializer < Api::V1::BaseSerializer
-
attribute :title
-
attribute :first_name
-
attribute :last_name
-
attribute :company_name
-
attribute :department
-
attribute :po_box
-
attribute :address1
-
attribute :address2
-
attribute :address3
-
attribute :city
-
attribute :state
-
attribute :country
-
attribute :postal_code
-
attribute :email
-
attribute :phone
-
attribute :ext
-
attribute :fax
-
attribute :registrant_type
-
end
-
class FolderTree
-
extend Memoist
-
-
attr_reader :full_tree, :selected_ids
-
-
def initialize(params)
-
@full_tree = []
-
@selected_ids = params[:selected_ids].is_a?(Array) ? params[:selected_ids] : [params[:selected_ids]].compact
-
@folder = params[:folder]
-
@certificate_order_ids = params[:certificate_order_ids]
-
@filtered_folder_ids = params[:folder_ids]
-
@full_tree = build_subtree(@folder, params[:tree_type])
-
end
-
-
def build_subtree(folder, tree_type)
-
Rails.cache.fetch("#{folder.cache_key}/#{tree_type}/build_subtree") do
-
folder_children = get_folder_children(folder)
-
children = folder_children ? folder_children.inject([]) {|all, child| all << build_subtree(child, tree_type) } : []
-
co_children = if %w{co_folders_index co_folders_index_modal}.include?(tree_type)
-
[]
-
else
-
build_cert_orders(folder)
-
end
-
-
data = get_data(folder, tree_type)
-
-
return {
-
id: get_id_format(folder),
-
icon: get_icon(folder),
-
text: get_folder_name(folder, tree_type, data),
-
type: 'folder',
-
li_attr: get_li_attr(folder),
-
data: data,
-
state: { opened: false },
-
children: (children + co_children).flatten
-
}
-
end
-
end
-
memoize :build_subtree
-
-
def get_folder_children(folder)
-
filter_children = folder.children
-
if filter_children.any? && @filtered_folder_ids && @filtered_folder_ids.any?
-
filter_children = filter_children.where(id: @filtered_folder_ids)
-
end
-
filter_children
-
end
-
-
def get_folder_name(folder, tree_type, options=nil)
-
if tree_type == 'co_folders_index'
-
"#{folder.name} <span class='folder-co-count'>#{options[:certificate_orders_count]}</span>".html_safe
-
else
-
folder.name
-
end
-
end
-
-
def build_cert_orders(folder)
-
files = []
-
cos = folder.cached_certificate_orders
-
-
if @certificate_order_ids && @certificate_order_ids.any?
-
cos = cos.where(id: @certificate_order_ids)
-
end
-
-
if cos.uniq.any?
-
cos.each do |co|
-
files << {
-
id: get_id_format(co),
-
text: co.ref,
-
icon: get_icon(co),
-
type: 'file',
-
li_attr: get_li_attr(co),
-
state: { opened: false },
-
data: get_data_certificate(co)
-
}
-
end
-
end
-
files
-
end
-
memoize :build_cert_orders
-
-
def get_icon(object)
-
if object.is_a?(Folder)
-
if object.default?
-
'fa fa-certificate'
-
elsif object.archived?
-
'fa fa-archive'
-
elsif object.expired?
-
'fa fa-history'
-
elsif object.active?
-
'fa fa-gear'
-
elsif object.revoked?
-
'fa fa-warning'
-
else
-
'jstree-folder'
-
end
-
else
-
'jstree-file'
-
end
-
end
-
-
def get_id_format(object)
-
object.is_a?(Folder) ? "#{object.id}_folder" : "#{object.ref}_cert"
-
end
-
-
def get_li_attr(object)
-
if object.is_a?(Folder)
-
klass = if object.default?
-
'jstree-folder-default'
-
elsif object.archived?
-
'jstree-folder-archive'
-
elsif object.active?
-
'jstree-folder-active'
-
elsif object.expired?
-
'jstree-folder-expired'
-
else
-
'jstree-folder-normal'
-
end
-
else
-
'jstree-co'
-
end
-
return { class: klass }
-
end
-
-
def get_data(folder, tree_type=nil)
-
data = {
-
archived: folder.archived?,
-
default: folder.default?,
-
expired: folder.expired?
-
}
-
if tree_type && tree_type == 'co_folders_index'
-
cos = get_data_certificates(folder)
-
data = data.merge(cos);
-
end
-
return data
-
end
-
-
def get_data_certificates(folder)
-
data = {certificate_orders: []}
-
list = folder.certificate_orders.uniq
-
list.each do |co|
-
data[:certificate_orders].push co_common_name(co)
-
end
-
data.merge(certificate_orders_count: list.count)
-
end
-
memoize :get_data_certificates
-
-
def get_data_certificate(co)
-
return {
-
ref: co.ref,
-
subject: co_common_name(co, true),
-
status: co_status(co),
-
expires: co_expires_on(co)
-
}
-
end
-
memoize :get_data_certificate
-
-
def co_status(co)
-
return if co.certificate_content.blank?
-
certificate_content = co.certificate_content
-
if co && certificate_content.new?
-
if co.is_expired?
-
'expired'
-
else
-
co.certificate.admin_submit_csr? ? 'info required' : 'waiting for csr'
-
end
-
elsif certificate_content.expired?
-
'expired'
-
elsif certificate_content.preferred_reprocessing?
-
'reprocess requested'
-
else
-
case certificate_content.workflow_state
-
when 'csr_submitted' then 'info required'
-
when 'info_provided' then 'contacts required'
-
when 'reprocess_requested' then 'csr required'
-
when 'contacts_provided' then 'validation required'
-
else
-
certificate_content.workflow_state.to_s.titleize.downcase
-
end
-
end
-
end
-
-
def co_expires_on(co)
-
return '' if co.certificate_content.csr.blank?
-
cc = co.certificate_content
-
if cc.new? || cc.csr.signed_certificate.blank? ||
-
cc.csr.signed_certificate.expiration_date.blank?
-
''
-
else
-
cc.csr.signed_certificate.expiration_date.strftime("%b %d, %Y")
-
end
-
end
-
-
def co_common_name(co, cn_only=false)
-
if co.is_expired_credit?
-
cn = "expired certificate"
-
else
-
cn = if co.is_unused_credit?
-
"credit - #{co.certificate.description['certificate_type']} certificate"
-
else
-
if co.certificate.is_code_signing?
-
co.registrant.try(:company_name) || "#{co.certificate.description['certificate_type']} certificate"
-
else
-
co.common_name
-
end
-
end
-
end
-
cn_only ? cn : "#{cn} (#{co.ref})"
-
end
-
end
-
require 'workflow'
-
-
Workflow::Adapter::ActiveRecord::InstanceMethods.module_eval do
-
# On transition the new workflow state is immediately saved in the
-
# database.
-
def persist_workflow_state(new_value)
-
# older Rails; beware of side effect: other (pending) attribute changes will be persisted too
-
update_attribute self.class.workflow_column, new_value
-
end
-
end
-
module ActiveRecord
-
class Base
-
def self.inherited(klass)
-
super
-
klass.send :has_many, :owner_system_audits, :as => :owner, class_name: "SystemAudit"
-
klass.send :has_many, :target_system_audits, :as => :target, class_name: "SystemAudit"
-
end
-
-
# UNION in Rails 4 https://stackoverflow.com/questions/6686920/activerecord-query-union
-
def system_audits
-
SystemAudit.from("(#{target_system_audits.to_sql} UNION #{owner_system_audits.to_sql}) AS system_audits")
-
end
-
end
-
end
-
class BillableMigrationGenerator < Rails::Generator::NamedBase
-
def manifest
-
record do |m|
-
m.migration_template 'migration.rb', 'db/migrate'
-
end
-
end
-
end
-
class <%= class_name %> < ActiveRecord::Migration
-
def self.up
-
create_table :gateways, :force => true do |t|
-
t.column :service, :string
-
t.column :login, :string
-
t.column :password, :string
-
t.column :mode, :string
-
end
-
-
create_table :line_items, :force => true do |t|
-
t.column :order_id, :integer
-
t.column :sellable_id, :integer
-
t.column :sellable_type, :string
-
t.column :cents, :integer
-
t.column :currency, :string
-
end
-
-
add_index :line_items, :order_id
-
add_index :line_items, :sellable_id
-
add_index :line_items, :sellable_type
-
-
create_table :orders, :force => true do |t|
-
t.column :billable_id, :integer
-
t.column :billable_type, :string
-
t.column :address_id, :integer
-
t.column :cents, :integer
-
t.column :currency, :string
-
t.column :created_at, :datetime
-
t.column :updated_at, :datetime
-
t.column :paid_at, :datetime
-
t.column :canceled_at, :datetime
-
t.column :lock_version, :integer, :default => 0
-
end
-
-
add_index :orders, :billable_id
-
add_index :orders, :billable_type
-
add_index :orders, :created_at
-
add_index :orders, :updated_at
-
-
create_table :payments, :force => true do |t|
-
t.column :order_id, :integer
-
t.column :address_id, :integer
-
t.column :cents, :integer
-
t.column :currency, :string
-
t.column :confirmation, :string
-
t.column :cleared_at, :datetime
-
t.column :voided_at, :datetime
-
t.column :created_at, :datetime
-
t.column :updated_at, :datetime
-
t.column :lock_version, :integer, :default => 0
-
end
-
-
add_index :payments, :order_id
-
add_index :payments, :cleared_at
-
add_index :payments, :created_at
-
add_index :payments, :updated_at
-
-
create_table :addresses, :force => true do |t|
-
t.column :name, :string
-
t.column :street1, :string
-
t.column :street2, :string
-
t.column :locality, :string
-
t.column :region, :string
-
t.column :postal_code, :string
-
t.column :country, :string
-
t.column :phone, :string
-
end
-
end
-
-
def self.down
-
drop_table :line_items
-
drop_table :orders
-
drop_table :payments
-
drop_table :gateways
-
drop_table :addresses
-
end
-
end
-
require 'active_merchant_default_gateway'
-
require 'acts_as_sellable'
-
require 'acts_as_seller'
-
require 'acts_as_billable'
-
-
ActiveRecord::Base.class_eval do
-
include CollectiveIdea::Acts::Billable
-
include CollectiveIdea::Acts::Sellable
-
end
-
1
module ActiveMerchant #:nodoc:
-
1
module Billing #:nodoc:
-
1
module Base
-
1
@@default_gateway = :bogus
-
1
@@default_gateway_options = {}
-
-
# set the default gateway and options
-
#
-
# ActiveMerchant::Billing::Base.set_default_gateway :bogus
-
#
-
# ActiveMerchant::Billing::Base.set_default_gateway :paypal, :login => 'fred', :password => 'flintstone'
-
1
def self.set_default_gateway(gateway, options = {})
-
@@default_gateway = gateway
-
@@default_gateway_options = options
-
end
-
-
# Get an instance of the default gateway
-
1
def self.default_gateway
-
ActiveMerchant::Billing::Base.gateway(@@default_gateway).new(@@default_gateway_options)
-
end
-
end
-
end
-
end
-
1
module CollectiveIdea #:nodoc:
-
1
module Acts #:nodoc:
-
1
module Billable #:nodoc:
-
-
1
def self.included(mod)
-
1
mod.extend(ClassMethods)
-
end
-
-
1
module ClassMethods
-
1
def acts_as_billable
-
1
include CollectiveIdea::Acts::Billable::InstanceMethods
-
1
class_eval do
-
1
has_many :orders, :as => :billable
-
end
-
end
-
end
-
-
1
module InstanceMethods
-
1
def purchase(*sellables)
-
sellables = sellables.flatten
-
raise ArgumentError.new("Sellable models must have a :price") unless sellables.all? {|sellable| sellable.respond_to? :price }
-
self.orders.build.tap do |order|
-
sellables.each do |sellable|
-
li=order.line_items.build :sellable => sellable
-
end
-
end
-
end
-
end
-
-
end
-
end
-
end
-
1
module CollectiveIdea #:nodoc:
-
1
module Acts #:nodoc:
-
1
module Sellable #:nodoc:
-
1
def self.included(mod)
-
1
mod.extend(ClassMethods)
-
end
-
-
1
module ClassMethods
-
-
# Declares a model as sellable
-
#
-
# A sellable model must have a field that stores the price in cents.
-
#
-
# === Options:
-
# * <tt>:cents</tt>: name of cents field (default :cents).
-
# * <tt>:currency</tt>: name of currency field (default :currency). Set to <tt>false</tt>
-
# diable storing the currency, causing it to default to USD
-
#
-
# === Example:
-
#
-
# class Product < ActiveRecord::Base
-
# acts_as_sellable :cents => :price_in_cents, :currency => false
-
# end
-
#
-
1
def acts_as_sellable(options = {})
-
2
class_eval do
-
2
include InstanceMethods
-
2
money :price, options
-
-
2
has_many :line_items, :as => :sellable
-
2
has_many :orders, :through => :line_items
-
end
-
end
-
-
1
def find_from_model_and_id model_string
-
model_and_id = model_string.split(/_(?=\d+$)/)
-
model = model_and_id[0].camelize.constantize
-
model.find(model_and_id[1].to_i)
-
end
-
end
-
-
1
module InstanceMethods
-
end
-
end
-
end
-
end
-
-
-
-
-
1
class Seller
-
1
cattr_accessor :default_gateway
-
1
attr_accessor :gateway
-
-
1
def initialize(attributes={})
-
self.gateway = attributes[:gateway]
-
end
-
-
end
-
class Gateway < ActiveRecord::Base
-
-
end
-
-
class LineItem < ActiveRecord::Base
-
belongs_to :order
-
belongs_to :sellable, :polymorphic => true
-
-
money :amount
-
-
# set #amount when adding sellable. This method is aliased to <tt>sellable=</tt>.
-
def sellable_with_price=(sellable)
-
self.amount = sellable && sellable.price ? sellable.price : 0
-
self.sellable_without_price = sellable
-
end
-
alias_method_chain :sellable=, :price
-
-
end
-
class Order < ActiveRecord::Base
-
belongs_to :billable, :polymorphic => true
-
belongs_to :address
-
has_many :line_items, :dependent => :destroy
-
has_many :payments
-
-
money :amount
-
before_create :total
-
-
def authorize(credit_card, options = {})
-
response = gateway.authorize(self.amount, credit_card, options_for_payment(options))
-
if response.success?
-
self.payments.build(:amount => self.amount, :confirmation => response.authorization,
-
:address => options[:billing_address])
-
else
-
payment_failed(response)
-
end
-
end
-
-
def pay(credit_card, options = {})
-
response = gateway.purchase(self.amount, credit_card, options_for_payment(options))
-
if response.success?
-
self.payments.build(:amount => self.amount,
-
:confirmation => response.authorization,
-
:cleared_at => Time.now,
-
:address => options[:billing_address]).tap do |payment|
-
self.paid_at = Time.now
-
payment.save && self.save unless new_record?
-
end
-
else
-
payment_failed(response)
-
end
-
end
-
-
def total
-
self.amount = line_items.inject(0.to_money) {|sum,l| sum + l.amount }
-
end
-
-
# TODO: Should this do more?
-
def cancel!
-
update_attribute :canceled_at, Time.now
-
end
-
-
private
-
-
def gateway
-
ActiveMerchant::Billing::Base.default_gateway
-
end
-
-
def payment_failed(response)
-
raise Payment::AuthorizationError.new(response.message)
-
end
-
-
def options_for_payment(options = {})
-
{:order_id => self.id, :customer => self.billable_id}.merge(options)
-
end
-
-
-
end
-
class Payment < ActiveRecord::Base
-
class AuthorizationError < StandardError; end
-
belongs_to :order
-
belongs_to :address
-
-
money :amount
-
-
def capture
-
response = ActiveMerchant::Billing::Base.default_gateway.capture(self.amount, self.confirmation)
-
update_attributes :cleared_at => Time.now, :confirmation => response.authorization
-
end
-
-
def void!
-
response = ActiveMerchant::Billing::Base.default_gateway.void(self.confirmation)
-
raise response.message unless response.success?
-
update_attribute :voided_at, Time.now
-
end
-
-
end
-
# Uninstall hook code here
-
1
require 'money'
-
-
1
module CollectiveIdea #:nodoc:
-
1
module Acts
-
1
module Money #:nodoc:
-
1
def self.included(base) #:nodoc:
-
1
base.extend ClassMethods
-
end
-
-
1
module ClassMethods
-
1
def money(name, options = {})
-
3
options = {:cents => :cents, :currency => :currency}.merge(options)
-
3
mapping = [[options[:cents].to_s, 'cents']]
-
3
mapping << [options[:currency].to_s, 'currency'] if options[:currency]
-
-
3
composed_of name, :class_name => 'Money', :allow_nil => true, :mapping => mapping do |m|
-
m.to_money
-
end
-
end
-
end
-
end
-
end
-
end
-
-
1
class Money
-
1
cattr_accessor :zero
-
-
1
def -@
-
Money.new(-@cents, @currency)
-
end
-
-
1
def blank?
-
zero?
-
end
-
-
1
def format_with_zero(*rules)
-
rules = rules.flatten
-
options = {}
-
options.update rules.pop if rules.last.is_a? Hash
-
-
if cents == 0
-
if options[:zero]
-
options[:zero]
-
elsif self.class.zero
-
self.class.zero
-
else
-
format = "$0"
-
format << ".00" unless rules.include?(:no_cents)
-
format
-
end
-
else
-
format_with_free(options)
-
end
-
end
-
1
alias_method :format_with_free, :format
-
1
alias_method :format, :format_with_zero
-
end
-
1
require 'active_record/reflection'
-
-
1
module ActiveRecord
-
1
module Aggregations # :nodoc:
-
1
def self.included(base)
-
base.extend(ClassMethods)
-
end
-
-
1
def clear_aggregation_cache #:nodoc:
-
self.class.reflect_on_all_aggregations.to_a.each do |assoc|
-
instance_variable_set "@#{assoc.name}", nil
-
end unless self.new_record?
-
end
-
-
# Active Record implements aggregation through a macro-like class method called +composed_of+ for representing attributes
-
# as value objects. It expresses relationships like "Account [is] composed of Money [among other things]" or "Person [is]
-
# composed of [an] address". Each call to the macro adds a description of how the value objects are created from the
-
# attributes of the entity object (when the entity is initialized either as a new object or from finding an existing object)
-
# and how it can be turned back into attributes (when the entity is saved to the database). Example:
-
#
-
# class Customer < ActiveRecord::Base
-
# composed_of :balance, :class_name => "Money", :mapping => %w(balance amount)
-
# composed_of :address, :mapping => [ %w(address_street street), %w(address_city city) ]
-
# end
-
#
-
# The customer class now has the following methods to manipulate the value objects:
-
# * <tt>Customer#balance, Customer#balance=(money)</tt>
-
# * <tt>Customer#address, Customer#address=(address)</tt>
-
#
-
# These methods will operate with value objects like the ones described below:
-
#
-
# class Money
-
# include Comparable
-
# attr_reader :amount, :currency
-
# EXCHANGE_RATES = { "USD_TO_DKK" => 6 }
-
#
-
# def initialize(amount, currency = "USD")
-
# @amount, @currency = amount, currency
-
# end
-
#
-
# def exchange_to(other_currency)
-
# exchanged_amount = (amount * EXCHANGE_RATES["#{currency}_TO_#{other_currency}"]).floor
-
# Money.new(exchanged_amount, other_currency)
-
# end
-
#
-
# def ==(other_money)
-
# amount == other_money.amount && currency == other_money.currency
-
# end
-
#
-
# def <=>(other_money)
-
# if currency == other_money.currency
-
# amount <=> amount
-
# else
-
# amount <=> other_money.exchange_to(currency).amount
-
# end
-
# end
-
# end
-
#
-
# class Address
-
# attr_reader :street, :city
-
# def initialize(street, city)
-
# @street, @city = street, city
-
# end
-
#
-
# def close_to?(other_address)
-
# city == other_address.city
-
# end
-
#
-
# def ==(other_address)
-
# city == other_address.city && street == other_address.street
-
# end
-
# end
-
#
-
# Now it's possible to access attributes from the database through the value objects instead. If you choose to name the
-
# composition the same as the attributes name, it will be the only way to access that attribute. That's the case with our
-
# +balance+ attribute. You interact with the value objects just like you would any other attribute, though:
-
#
-
# customer.balance = Money.new(20) # sets the Money value object and the attribute
-
# customer.balance # => Money value object
-
# customer.balance.exchanged_to("DKK") # => Money.new(120, "DKK")
-
# customer.balance > Money.new(10) # => true
-
# customer.balance == Money.new(20) # => true
-
# customer.balance < Money.new(5) # => false
-
#
-
# Value objects can also be composed of multiple attributes, such as the case of Address. The order of the mappings will
-
# determine the order of the parameters. Example:
-
#
-
# customer.address_street = "Hyancintvej"
-
# customer.address_city = "Copenhagen"
-
# customer.address # => Address.new("Hyancintvej", "Copenhagen")
-
# customer.address = Address.new("May Street", "Chicago")
-
# customer.address_street # => "May Street"
-
# customer.address_city # => "Chicago"
-
#
-
# == Writing value objects
-
#
-
# Value objects are immutable and interchangeable objects that represent a given value, such as a Money object representing
-
# $5. Two Money objects both representing $5 should be equal (through methods such as == and <=> from Comparable if ranking
-
# makes sense). This is unlike entity objects where equality is determined by identity. An entity class such as Customer can
-
# easily have two different objects that both have an address on Hyancintvej. Entity identity is determined by object or
-
# relational unique identifiers (such as primary keys). Normal ActiveRecord::Base classes are entity objects.
-
#
-
# It's also important to treat the value objects as immutable. Don't allow the Money object to have its amount changed after
-
# creation. Create a new money object with the new value instead. This is exemplified by the Money#exchanged_to method that
-
# returns a new value object instead of changing its own values. Active Record won't persist value objects that have been
-
# changed through other means than the writer method.
-
#
-
# The immutable requirement is enforced by Active Record by freezing any object assigned as a value object. Attempting to
-
# change it afterwards will result in a TypeError.
-
#
-
# Read more about value objects on http://c2.com/cgi/wiki?ValueObject and on the dangers of not keeping value objects
-
# immutable on http://c2.com/cgi/wiki?ValueObjectsShouldBeImmutable
-
1
module ClassMethods
-
# Adds reader and writer methods for manipulating a value object:
-
# <tt>composed_of :address</tt> adds <tt>address</tt> and <tt>address=(new_address)</tt> methods.
-
#
-
# Options are:
-
# * <tt>:class_name</tt> - specify the class name of the association. Use it only if that name can't be inferred
-
# from the part id. So <tt>composed_of :address</tt> will by default be linked to the +Address+ class, but
-
# if the real class name is +CompanyAddress+, you'll have to specify it with this option.
-
# * <tt>:mapping</tt> - specifies a number of mapping arrays (attribute, parameter) that bind an attribute name
-
# to a constructor parameter on the value class.
-
# * <tt>:allow_nil</tt> - specifies that the aggregate object will not be instantiated when all mapped
-
# attributes are nil. Setting the aggregate class to nil has the effect of writing nil to all mapped attributes.
-
# This defaults to false.
-
#
-
# An optional block can be passed to convert the argument that is passed to the writer method into an instance of
-
# <tt>:class_name</tt>. The block will only be called if the argument is not already an instance of <tt>:class_name</tt>.
-
#
-
# Option examples:
-
# composed_of :temperature, :mapping => %w(reading celsius)
-
# composed_of(:balance, :class_name => "Money", :mapping => %w(balance amount)) {|balance| balance.to_money }
-
# composed_of :address, :mapping => [ %w(address_street street), %w(address_city city) ]
-
# composed_of :gps_location
-
# composed_of :gps_location, :allow_nil => true
-
#
-
1
def composed_of(part_id, options = {}, &block)
-
3
options.assert_valid_keys(:class_name, :mapping, :allow_nil)
-
-
3
name = part_id.id2name
-
3
class_name = options[:class_name] || name.camelize
-
3
mapping = options[:mapping] || [ name, name ]
-
3
mapping = [ mapping ] unless mapping.first.is_a?(Array)
-
3
allow_nil = options[:allow_nil] || false
-
-
3
reader_method(name, class_name, mapping, allow_nil)
-
3
writer_method(name, class_name, mapping, allow_nil, block)
-
-
3
ActiveRecord::Reflection.create(:composed_of, part_id, nil, options, self)
-
end
-
-
1
private
-
1
def reader_method(name, class_name, mapping, allow_nil)
-
3
module_eval do
-
3
define_method(name) do |*args|
-
force_reload = args.first || false
-
if (instance_variable_get("@#{name}").nil? || force_reload) && (!allow_nil || mapping.any? {|pair| !read_attribute(pair.first).nil? })
-
instance_variable_set("@#{name}", class_name.constantize.new(*mapping.collect {|pair| read_attribute(pair.first)}))
-
end
-
return instance_variable_get("@#{name}")
-
end
-
-
3
define_method("#{name}?") do
-
!self.send(name).blank?
-
end
-
end
-
-
end
-
-
1
def writer_method(name, class_name, mapping, allow_nil, conversion)
-
3
module_eval do
-
3
define_method("#{name}=") do |part|
-
if part.nil? && allow_nil
-
mapping.each { |pair| assign_attributes({(pair.first).to_sym => nil}, without_protection: true) }
-
instance_variable_set("@#{name}", nil)
-
else
-
part = conversion.call(part) unless part.is_a?(class_name.constantize) || conversion.nil?
-
mapping.each { |pair| assign_attributes({(pair.first).to_sym => part.send(pair.last)}, without_protection: true) }
-
instance_variable_set("@#{name}", part.freeze)
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
class NoteGenerator < Rails::Generator::Base
-
def manifest
-
record do |m|
-
m.directory 'app/models'
-
m.file 'note.rb', 'app/models/note.rb'
-
m.migration_template "create_notes.rb", "db/migrate"
-
end
-
end
-
# ick what a hack.
-
def file_name
-
"create_notes"
-
end
-
end
-
class CreateNotes < ActiveRecord::Migration
-
def self.up
-
create_table :notes do |t|
-
t.string :title, :limit => 50, :default => ""
-
t.text :note, :default => ""
-
t.references :notable, :polymorphic => true
-
t.references :user
-
t.timestamps
-
end
-
-
add_index :notes, :notable_type
-
add_index :notes, :notable_id
-
add_index :notes, :user_id
-
end
-
-
def self.down
-
drop_table :notes
-
end
-
end
-
class Note < ActiveRecord::Base
-
-
include ActsAsNotable::Note
-
-
belongs_to :notable, :polymorphic => true
-
-
default_scope{ :order => 'created_at ASC'}
-
-
# NOTE: install the acts_as_votable plugin if you
-
# want user to vote on the quality of notes.
-
#acts_as_voteable
-
-
# NOTE: Notes belong to a user
-
belongs_to :user
-
-
end
-
require File.join(File.dirname(__FILE__), 'rails', 'init')
-
puts "To create the note model please run:"
-
puts "script/generate note"
-
1
require 'active_record'
-
-
# ActsAsNotable
-
1
module Juixe
-
1
module Acts #:nodoc:
-
1
module Notable #:nodoc:
-
-
1
def self.included(base)
-
1
base.extend ClassMethods
-
end
-
-
1
module ClassMethods
-
1
def acts_as_notable
-
has_many :notes, :as => :notable, :dependent => :destroy
-
include Juixe::Acts::Notable::InstanceMethods
-
extend Juixe::Acts::Notable::SingletonMethods
-
end
-
end
-
-
# This module contains class methods
-
1
module SingletonMethods
-
# Helper method to lookup for notes for a given object.
-
# This method is equivalent to obj.notes.
-
1
def find_notes_for(obj)
-
notable = ActiveRecord::Base.send(:class_name_of_active_record_descendant, self).to_s
-
-
Note.find(:all,
-
:conditions => ["notable_id = ? and notable_type = ?", obj.id, notable],
-
:order => "created_at DESC"
-
)
-
end
-
-
# Helper class method to lookup notes for
-
# the mixin notable type written by a given user.
-
# This method is NOT equivalent to Note.find_notes_for_user
-
1
def find_notes_by_user(user)
-
notable = ActiveRecord::Base.send(:class_name_of_active_record_descendant, self).to_s
-
-
Note.find(:all,
-
:conditions => ["user_id = ? and notable_type = ?", user.id, notable],
-
:order => "created_at DESC"
-
)
-
end
-
end
-
-
# This module contains instance methods
-
1
module InstanceMethods
-
# Helper method to sort notes by date
-
1
def notes_ordered_by_submitted
-
Note.find(:all,
-
:conditions => ["notable_id = ? and notable_type = ?", id, self.class.name],
-
:order => "created_at DESC"
-
)
-
end
-
-
# Helper method that defaults the submitted time.
-
1
def add_note(note)
-
notes << note
-
end
-
end
-
-
end
-
end
-
end
-
-
1
ActiveRecord::Base.send(:include, Juixe::Acts::Notable)
-
1
module ActsAsNotable
-
# including this module into your Note model will give you finders and named scopes
-
# useful for working with Notes.
-
# The named scopes are:
-
# in_order: Returns notes in the order they were created (created_at ASC).
-
# recent: Returns notes by how recently they were created (created_at DESC).
-
# limit(N): Return no more than N notes.
-
1
module Note
-
-
1
def self.included(note_model)
-
note_model.extend Finders
-
note_model.scope :in_order, lambda{order("created_at asc")}
-
note_model.scope :recent, lambda{order("created_at desc")}
-
# note_model.scope :limit, lambda {|limit| {:limit => limit}}
-
end
-
-
1
module Finders
-
# Helper class method to lookup all notes assigned
-
# to all notable types for a given user.
-
1
def find_notes_by_user(user)
-
find(:all,
-
:conditions => ["user_id = ?", user.id],
-
:order => "created_at DESC"
-
)
-
end
-
-
# Helper class method to look up all notes for
-
# notable class name and notable id.
-
1
def find_notes_for_notable(notable_str, notable_id)
-
find(:all,
-
:conditions => ["notable_type = ? and notable_id = ?", notable_str, notable_id],
-
:order => "created_at DESC"
-
)
-
end
-
-
# Helper class method to look up a notable object
-
# given the notable class name and id
-
1
def find_notable(notable_str, notable_id)
-
notable_str.constantize.find(notable_id)
-
end
-
end
-
end
-
end
-
require File.join(File.dirname(__FILE__), '..', 'lib', 'acts_as_notable')
-
-
class PublishingGenerator < Rails::Generator::Base
-
-
attr_reader :publishing_class
-
attr_reader :publishing_table_name
-
-
def initialize(args, options = {})
-
klass = args.last
-
-
begin; valid_klass = klass.camelcase.constantize; rescue; end
-
-
if valid_klass
-
@publishing_table_name = klass.to_s.downcase.pluralize
-
@publishing_class = klass.to_s.capitalize
-
else
-
raise "#{klass} is not a valid class in this application."
-
end
-
-
super
-
end
-
-
def manifest
-
record do |m|
-
unless options[:skip_migration]
-
m.migration_template 'migration.rb', 'db/migrate',
-
:migration_file_name => "add_published_as_to_#{@publishing_table_name}"
-
end
-
end
-
end
-
-
protected
-
def usage
-
puts "Usage: #{$0} publishing [ModelName]"
-
end
-
end
-
class AddPublishedAsTo<%= publishing_class.pluralize %> < ActiveRecord::Migration
-
-
# Add the new tables.
-
def self.up
-
add_column :<%= publishing_table_name %>, :published_as, :string, :limit => 16, :default => 'draft'
-
end
-
-
# Remove the tables.
-
def self.down
-
remove_column :<%= publishing_table_name %>, :published_as
-
end
-
-
end
-
# require 'acts_as_publishable'
-
# ActiveRecord::Base.send(:include, Acts::As::Publishable)
-
#
-
1
module Acts
-
1
module As
-
1
module Publishable
-
-
1
def self.included(base)
-
1
base.extend(ClassMethods)
-
-
# All ActiveRecords will now respond to publishable? with false
-
1
def publishable?; false; end
-
end
-
-
1
module ClassMethods
-
1
def acts_as_publishable(*args)
-
unless args.include?(:draft) && args.include?(:live)
-
raise "you must specify :draft and :live in list of publish_states for acts_as_publishable"
-
end
-
-
cattr_accessor :publish_states
-
self.publish_states = args.collect{|state| state.to_s.downcase.to_sym }
-
include InstanceMethods
-
-
-
class << self
-
alias_method_chain :find, :published_as
-
end
-
-
# create methods for each publish state
-
self.publish_states.each do |status|
-
-
define_method("is_#{status}?") do
-
self.published_as == status.to_s
-
end
-
-
define_method("save_as_#{status}") do
-
self.published_as = status.to_s
-
save
-
end
-
-
end
-
end
-
-
1
def find_with_published_as(*args)
-
# hacked to filter out unpublished items by default, when using find(:all)
-
# to really find all items, use Class.find_without_published_as
-
state = args.first
-
state = state.eql?(:all) ? :live : state
-
-
if self.publish_states.include?(state)
-
args.shift
-
# find_all_by_published_as(state.to_s.downcase, *args)
-
# again, hacked
-
where(published_as: state.to_s.downcase).scoping do
-
find_without_published_as(:all, *args)
-
end
-
else
-
find_without_published_as(*args)
-
end
-
end
-
-
end
-
-
1
module InstanceMethods
-
-
# All ActiveRecords using this plugin will now respond to publishable? with true
-
1
def publishable?; true; end
-
-
1
def publish(should_raise = false)
-
if defined?(:save_as_live)
-
save_as_live
-
else
-
raise "Add 'live' to list of acts_as_published for publish method" if should_raise
-
end
-
end
-
-
end
-
end
-
end
-
end
-
# Uninstall hook code here
-
Array.class_eval do
-
def will_paginate(page=1, per_page=15)
-
pagination_array = WillPaginate::Collection.new(page, per_page, self.size)
-
start_index = pagination_array.offset
-
end_index = start_index + (per_page - 1)
-
array_to_concat = self[start_index..end_index]
-
array_to_concat.nil? ? [] : pagination_array.concat(array_to_concat)
-
end
-
-
def find_dups
-
uniq.map {|v| (self - [v]).size < (self.size - 1) ? v : nil}.compact
-
end
-
end
-
# Extend img tag to use the alt text for the title attribute if alt is present & title is empty (for SEO)
-
ActionView::Helpers::AssetTagHelper.module_eval do
-
alias_method :orig_image_tag, :image_tag
-
def image_tag(source, options = {})
-
if options[:alt] && !options[:title]
-
options[:title] = options[:alt]
-
end
-
return orig_image_tag(source, options)
-
end
-
end
-
-
ActionView::Helpers::UrlHelper.module_eval do
-
alias_method :orig_url_for, :url_for
-
def url_for(options={})
-
options.reverse_merge!({subdomain: false}) if options.is_a?(Hash)
-
return orig_url_for(options)
-
end
-
end
-
ActiveRecord::Base.class_eval do
-
def model_and_id
-
[self.class.to_s.underscore, self.id].join("_")
-
end
-
end
-
module CertificateProperties
-
-
def openssl_x509
-
begin
-
OpenSSL::X509::Certificate.new(body.strip)
-
rescue Exception
-
end
-
end
-
-
def issuer_dn
-
openssl_x509.issuer.to_s(OpenSSL::X509::Name::RFC2253)
-
end
-
-
def dn
-
openssl_x509.subject.to_s
-
end
-
-
end
-
-
-
class DomainConstraint
-
def initialize(domain)
-
@domains = [domain].flatten
-
end
-
-
def matches?(request)
-
@domains.include? request.host
-
end
-
end
-
require 'action_view/helpers'
-
require 'active_support/i18n'
-
require 'active_support/core_ext/enumerable'
-
require 'active_support/core_ext/object/blank'
-
-
module ActionView
-
module Helpers
-
# The Active Record Helper makes it easier to create forms for records kept in instance variables. The most far-reaching is the +form+
-
# method that creates a complete form for all the basic content types of the record (not associations or aggregations, though). This
-
# is a great way of making the record quickly available for editing, but likely to prove lackluster for a complicated real-world form.
-
# In that case, it's better to use the +input+ method and the specialized +form+ methods in link:classes/ActionView/Helpers/FormHelper.html
-
module DynamicForm
-
# Returns a default input tag for the type of object returned by the method. For example, if <tt>@post</tt>
-
# has an attribute +title+ mapped to a +VARCHAR+ column that holds "Hello World":
-
#
-
# input("post", "title")
-
# # => <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
-
def input(record_name, method, options = {})
-
InstanceTag.new(record_name, method, self).to_tag(options)
-
end
-
-
# Returns an entire form with all needed input tags for a specified Active Record object. For example, if <tt>@post</tt>
-
# has attributes named +title+ of type +VARCHAR+ and +body+ of type +TEXT+ then
-
#
-
# form("post")
-
#
-
# would yield a form like the following (modulus formatting):
-
#
-
# <form action='/posts/create' method='post'>
-
# <p>
-
# <label for="post_title">Title</label><br />
-
# <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
-
# </p>
-
# <p>
-
# <label for="post_body">Body</label><br />
-
# <textarea cols="40" id="post_body" name="post[body]" rows="20"></textarea>
-
# </p>
-
# <input name="commit" type="submit" value="Create" />
-
# </form>
-
#
-
# It's possible to specialize the form builder by using a different action name and by supplying another
-
# block renderer. For example, if <tt>@entry</tt> has an attribute +message+ of type +VARCHAR+ then
-
#
-
# form("entry",
-
# :action => "sign",
-
# :input_block => Proc.new { |record, column|
-
# "#{column.human_name}: #{input(record, column.name)}<br />"
-
# })
-
#
-
# would yield a form like the following (modulus formatting):
-
#
-
# <form action="/entries/sign" method="post">
-
# Message:
-
# <input id="entry_message" name="entry[message]" size="30" type="text" /><br />
-
# <input name="commit" type="submit" value="Sign" />
-
# </form>
-
#
-
# It's also possible to add additional content to the form by giving it a block, such as:
-
#
-
# form("entry", :action => "sign") do |form|
-
# form << content_tag("b", "Department")
-
# form << collection_select("department", "id", @departments, "id", "name")
-
# end
-
#
-
# The following options are available:
-
#
-
# * <tt>:action</tt> - The action used when submitting the form (default: +create+ if a new record, otherwise +update+).
-
# * <tt>:input_block</tt> - Specialize the output using a different block, see above.
-
# * <tt>:method</tt> - The method used when submitting the form (default: +post+).
-
# * <tt>:multipart</tt> - Whether to change the enctype of the form to "multipart/form-data", used when uploading a file (default: +false+).
-
# * <tt>:submit_value</tt> - The text of the submit button (default: "Create" if a new record, otherwise "Update").
-
def form(record_name, options = {})
-
record = instance_variable_get("@#{record_name}")
-
record = convert_to_model(record)
-
-
options = options.symbolize_keys
-
options[:action] ||= record.persisted? ? "update" : "create"
-
action = url_for(:action => options[:action], :id => record)
-
-
submit_value = options[:submit_value] || options[:action].gsub(/[^\w]/, '').capitalize
-
-
contents = form_tag({:action => action}, :method =>(options[:method] || 'post'), :enctype => options[:multipart] ? 'multipart/form-data': nil)
-
contents.safe_concat hidden_field(record_name, :id) if record.persisted?
-
contents.safe_concat all_input_tags(record, record_name, options)
-
yield contents if block_given?
-
contents.safe_concat submit_tag(submit_value)
-
contents.safe_concat('</form>')
-
end
-
-
# Returns a string containing the error message attached to the +method+ on the +object+ if one exists.
-
# This error message is wrapped in a <tt>DIV</tt> tag by default or with <tt>:html_tag</tt> if specified,
-
# which can be extended to include a <tt>:prepend_text</tt> and/or <tt>:append_text</tt> (to properly explain
-
# the error), and a <tt>:css_class</tt> to style it accordingly. +object+ should either be the name of an
-
# instance variable or the actual object. The method can be passed in either as a string or a symbol.
-
# As an example, let's say you have a model <tt>@post</tt> that has an error message on the +title+ attribute:
-
#
-
# <%= error_message_on "post", "title" %>
-
# # => <div class="formError">can't be empty</div>
-
#
-
# <%= error_message_on @post, :title %>
-
# # => <div class="formError">can't be empty</div>
-
#
-
# <%= error_message_on "post", "title",
-
# :prepend_text => "Title simply ",
-
# :append_text => " (or it won't work).",
-
# :html_tag => "span",
-
# :css_class => "inputError" %>
-
# # => <span class="inputError">Title simply can't be empty (or it won't work).</span>
-
def error_message_on(object, method, *args)
-
options = args.extract_options!
-
unless args.empty?
-
ActiveSupport::Deprecation.warn('error_message_on takes an option hash instead of separate ' +
-
'prepend_text, append_text, html_tag, and css_class arguments', caller)
-
-
options[:prepend_text] = args[0] || ''
-
options[:append_text] = args[1] || ''
-
options[:html_tag] = args[2] || 'div'
-
options[:css_class] = args[3] || 'formError'
-
end
-
options.reverse_merge!(:prepend_text => '', :append_text => '', :html_tag => 'div', :css_class => 'formError')
-
-
object = convert_to_model(object)
-
-
if (obj = (object.respond_to?(:errors) ? object : instance_variable_get("@#{object}"))) &&
-
(errors = obj.errors[method]).presence
-
content_tag(options[:html_tag],
-
(options[:prepend_text].html_safe << errors.first).safe_concat(options[:append_text]),
-
:class => options[:css_class]
-
)
-
else
-
''
-
end
-
end
-
-
# Returns a string with a <tt>DIV</tt> containing all of the error messages for the objects located as instance variables by the names
-
# given. If more than one object is specified, the errors for the objects are displayed in the order that the object names are
-
# provided.
-
#
-
# This <tt>DIV</tt> can be tailored by the following options:
-
#
-
# * <tt>:header_tag</tt> - Used for the header of the error div (default: "h2").
-
# * <tt>:id</tt> - The id of the error div (default: "errorExplanation").
-
# * <tt>:class</tt> - The class of the error div (default: "errorExplanation").
-
# * <tt>:object</tt> - The object (or array of objects) for which to display errors,
-
# if you need to escape the instance variable convention.
-
# * <tt>:object_name</tt> - The object name to use in the header, or any text that you prefer.
-
# If <tt>:object_name</tt> is not set, the name of the first object will be used.
-
# * <tt>:header_message</tt> - The message in the header of the error div. Pass +nil+
-
# or an empty string to avoid the header message altogether. (Default: "X errors
-
# prohibited this object from being saved").
-
# * <tt>:message</tt> - The explanation message after the header message and before
-
# the error list. Pass +nil+ or an empty string to avoid the explanation message
-
# altogether. (Default: "There were problems with the following fields:").
-
#
-
# To specify the display for one object, you simply provide its name as a parameter.
-
# For example, for the <tt>@user</tt> model:
-
#
-
# error_messages_for 'user'
-
#
-
# You can also supply an object:
-
#
-
# error_messages_for @user
-
#
-
# This will use the last part of the model name in the presentation. For instance, if
-
# this is a MyKlass::User object, this will use "user" as the name in the String. This
-
# is taken from MyKlass::User.model_name.human, which can be overridden.
-
#
-
# To specify more than one object, you simply list them; optionally, you can add an extra <tt>:object_name</tt> parameter, which
-
# will be the name used in the header message:
-
#
-
# error_messages_for 'user_common', 'user', :object_name => 'user'
-
#
-
# You can also use a number of objects, which will have the same naming semantics
-
# as a single object.
-
#
-
# error_messages_for @user, @post
-
#
-
# If the objects cannot be located as instance variables, you can add an extra <tt>:object</tt> parameter which gives the actual
-
# object (or array of objects to use):
-
#
-
# error_messages_for 'user', :object => @question.user
-
#
-
# NOTE: This is a pre-packaged presentation of the errors with embedded strings and a certain HTML structure. If what
-
# you need is significantly different from the default presentation, it makes plenty of sense to access the <tt>object.errors</tt>
-
# instance yourself and set it up. View the source of this method to see how easy it is.
-
def error_messages_for(*params)
-
options = params.extract_options!.symbolize_keys
-
-
objects = Array.wrap(options.delete(:object) || params).map do |object|
-
object = instance_variable_get("@#{object}") unless object.respond_to?(:to_model)
-
object = convert_to_model(object)
-
-
if object.class.respond_to?(:model_name)
-
options[:object_name] ||= object.class.model_name.human.downcase
-
end
-
-
object
-
end
-
-
objects.compact!
-
count = objects.inject(0) {|sum, object| sum + object.errors.count }
-
-
unless count.zero?
-
html = {}
-
[:id, :class].each do |key|
-
if options.include?(key)
-
value = options[key]
-
html[key] = value unless value.blank?
-
else
-
html[key] = 'errorExplanation'
-
end
-
end
-
options[:object_name] ||= params.first
-
-
I18n.with_options :locale => options[:locale], :scope => [:errors, :template] do |locale|
-
header_message = if options.include?(:header_message)
-
options[:header_message]
-
else
-
locale.t :header, :count => count, :model => options[:object_name].to_s.gsub('_', ' ')
-
end
-
-
message = options.include?(:message) ? options[:message] : locale.t(:body)
-
-
error_messages = objects.sum do |object|
-
object.errors.full_messages.map do |msg|
-
content_tag(:li, msg)
-
end
-
end.join.html_safe
-
-
contents = ''
-
contents << content_tag(options[:header_tag] || :h2, header_message) unless header_message.blank?
-
contents << content_tag(:p, message) unless message.blank?
-
contents << content_tag(:ul, error_messages)
-
-
content_tag(:div, contents.html_safe, html)
-
end
-
else
-
''
-
end
-
end
-
-
private
-
-
def all_input_tags(record, record_name, options)
-
input_block = options[:input_block] || default_input_block
-
record.class.content_columns.collect{ |column| input_block.call(record_name, column) }.join("\n")
-
end
-
-
def default_input_block
-
Proc.new { |record, column| %(<p><label for="#{record}_#{column.name}">#{column.human_name}</label><br />#{input(record, column.name)}</p>) }
-
end
-
-
module InstanceTagMethods
-
def to_tag(options = {})
-
case column_type
-
when :string
-
field_type = @method_name.include?("password") ? "password" : "text"
-
to_input_field_tag(field_type, options)
-
when :text
-
to_text_area_tag(options)
-
when :integer, :float, :decimal
-
to_input_field_tag("text", options)
-
when :date
-
to_date_select_tag(options)
-
when :datetime, :timestamp
-
to_datetime_select_tag(options)
-
when :time
-
to_time_select_tag(options)
-
when :boolean
-
to_boolean_select_tag(options)
-
end
-
end
-
-
def column_type
-
object.send(:column_for_attribute, @method_name).type
-
end
-
end
-
-
module FormBuilderMethods
-
def error_message_on(method, *args)
-
@template.error_message_on(@object || @object_name, method, *args)
-
end
-
-
def error_messages(options = {})
-
@template.error_messages_for(@object_name, objectify_options(options))
-
end
-
end
-
end
-
-
class InstanceTag
-
include DynamicForm::InstanceTagMethods
-
end
-
-
class FormBuilder
-
include DynamicForm::FormBuilderMethods
-
end
-
end
-
end
-
-
I18n.load_path << File.expand_path("../../locale/en.yml", __FILE__)
-
require 'action_view/helpers/dynamic_form'
-
-
class ActionView::Base
-
include DynamicForm
-
end
-
FireWatir::Firefox.class_eval do
-
def url
-
@window_url = js_eval "#{document_var}.URL"
-
end
-
-
def status
-
js_status = js_eval("window.status")
-
js_status.empty? ? js_eval("window.XULBrowserWindow.statusText;") : js_status
-
end
-
end
-
class ForceSSL
-
def initialize(app)
-
@app = app
-
end
-
-
def call(env)
-
env["HTTP_ACCEPT"] = "text/html" if env["HTTP_ACCEPT"] == "text/*"
-
if env['HTTPS'] == 'on' || env['HTTP_X_FORWARDED_PROTO'] == 'https'# || other_exception(env)
-
@app.call(env)
-
else
-
req = Rack::Request.new(env)
-
[301, { "Location" => req.url.gsub(/\Ahttp:/, "https:") }, []]
-
end
-
end
-
-
def other_exception(env)
-
#need to be able to allow link.ssl.com and ssl.com without ssl
-
!!(env["HTTP_HOST"] =~ /\Assl.com(:\d+)?/ && env["PATH_INFO"]=~/\/.+/)
-
end
-
end
-
class Hash
-
def to_utf8
-
Hash[
-
self.collect do |k, v|
-
if (v.respond_to?(:to_utf8))
-
[ k, v.to_utf8 ]
-
elsif (v.respond_to?(:force_encoding))
-
[ k, v.dup.force_encoding("ISO-8859-1").encode("UTF-8") ]
-
else
-
[ k, v ]
-
end
-
end
-
]
-
end
-
end
-
ActionController::Base.send :include, InPlaceEditing
-
ActionController::Base.helper InPlaceMacrosHelper
-
1
module InPlaceEditing
-
1
def self.included(base)
-
1
base.extend(ClassMethods)
-
end
-
-
# Example:
-
#
-
# # Controller
-
# class BlogController < ApplicationController
-
# in_place_edit_for :post, :title
-
# end
-
#
-
# # View
-
# <%= in_place_editor_field :post, 'title' %>
-
#
-
1
module ClassMethods
-
1
def in_place_edit_for(object, attribute, options = {})
-
define_method("set_#{object}_#{attribute}") do
-
unless [:post, :put].include?(request.method) then
-
return render(:text => 'Method not allowed', :status => 405)
-
end
-
@item = object.to_s.camelize.constantize.find(params[:id])
-
@item.update_attribute(attribute, params[:value])
-
render :text => CGI::escapeHTML(@item.send(attribute).to_s)
-
end
-
end
-
end
-
end
-
1
module InPlaceMacrosHelper
-
# Makes an HTML element specified by the DOM ID +field_id+ become an in-place
-
# editor of a property.
-
#
-
# A form is automatically created and displayed when the user clicks the element,
-
# something like this:
-
# <form id="myElement-in-place-edit-form" target="specified url">
-
# <input name="value" text="The content of myElement"/>
-
# <input type="submit" value="ok"/>
-
# <a onclick="javascript to cancel the editing">cancel</a>
-
# </form>
-
#
-
# The form is serialized and sent to the server using an AJAX call, the action on
-
# the server should process the value and return the updated value in the body of
-
# the reponse. The element will automatically be updated with the changed value
-
# (as returned from the server).
-
#
-
# Required +options+ are:
-
# <tt>:url</tt>:: Specifies the url where the updated value should
-
# be sent after the user presses "ok".
-
#
-
# Addtional +options+ are:
-
# <tt>:rows</tt>:: Number of rows (more than 1 will use a TEXTAREA)
-
# <tt>:cols</tt>:: Number of characters the text input should span (works for both INPUT and TEXTAREA)
-
# <tt>:size</tt>:: Synonym for :cols when using a single line text input.
-
# <tt>:cancel_text</tt>:: The text on the cancel link. (default: "cancel")
-
# <tt>:save_text</tt>:: The text on the save link. (default: "ok")
-
# <tt>:loading_text</tt>:: The text to display while the data is being loaded from the server (default: "Loading...")
-
# <tt>:saving_text</tt>:: The text to display when submitting to the server (default: "Saving...")
-
# <tt>:external_control</tt>:: The id of an external control used to enter edit mode.
-
# <tt>:load_text_url</tt>:: URL where initial value of editor (content) is retrieved.
-
# <tt>:options</tt>:: Pass through options to the AJAX call (see prototype's Ajax.Updater)
-
# <tt>:with</tt>:: JavaScript snippet that should return what is to be sent
-
# in the AJAX call, +form+ is an implicit parameter
-
# <tt>:script</tt>:: Instructs the in-place editor to evaluate the remote JavaScript response (default: false)
-
# <tt>:click_to_edit_text</tt>::The text shown during mouseover the editable text (default: "Click to edit")
-
1
def in_place_editor(field_id, options = {})
-
function = "new Ajax.InPlaceEditor("
-
function << "'#{field_id}', "
-
function << "'#{url_for(options[:url])}'"
-
-
js_options = {}
-
-
if protect_against_forgery?
-
options[:with] ||= "Form.serialize(form)"
-
options[:with] += " + '&authenticity_token=' + encodeURIComponent('#{form_authenticity_token}')"
-
end
-
-
js_options['cancelText'] = %('#{options[:cancel_text]}') if options[:cancel_text]
-
js_options['okText'] = %('#{options[:save_text]}') if options[:save_text]
-
js_options['loadingText'] = %('#{options[:loading_text]}') if options[:loading_text]
-
js_options['savingText'] = %('#{options[:saving_text]}') if options[:saving_text]
-
js_options['rows'] = options[:rows] if options[:rows]
-
js_options['cols'] = options[:cols] if options[:cols]
-
js_options['size'] = options[:size] if options[:size]
-
js_options['externalControl'] = "'#{options[:external_control]}'" if options[:external_control]
-
js_options['loadTextURL'] = "'#{url_for(options[:load_text_url])}'" if options[:load_text_url]
-
js_options['ajaxOptions'] = options[:options] if options[:options]
-
js_options['htmlResponse'] = !options[:script] if options[:script]
-
js_options['callback'] = "function(form) { return #{options[:with]} }" if options[:with]
-
js_options['clickToEditText'] = %('#{options[:click_to_edit_text]}') if options[:click_to_edit_text]
-
js_options['textBetweenControls'] = %('#{options[:text_between_controls]}') if options[:text_between_controls]
-
function << (', ' + options_for_javascript(js_options)) unless js_options.empty?
-
-
function << ')'
-
-
javascript_tag(function)
-
end
-
-
# Renders the value of the specified object and method with in-place editing capabilities.
-
1
def in_place_editor_field(object, method, tag_options = {}, in_place_editor_options = {})
-
instance_tag = ::ActionView::Helpers::InstanceTag.new(object, method, self)
-
tag_options = {:tag => "span",
-
:id => "#{object}_#{method}_#{instance_tag.object.id}_in_place_editor",
-
:class => "in_place_editor_field"}.merge!(tag_options)
-
in_place_editor_options[:url] = in_place_editor_options[:url] || url_for({ :action => "set_#{object}_#{method}", :id => instance_tag.object.id })
-
tag = content_tag(tag_options.delete(:tag), h(instance_tag.value(instance_tag.object)),tag_options)
-
return tag + in_place_editor(tag_options[:id], in_place_editor_options)
-
end
-
end
-
module InWords
-
words = %w(zero one two three four five six seven eight nine)
-
words += %w(ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen)
-
%w(twenty thirty fourty fifty sixty seventy eighty ninety).each { |tens| words += [tens] + words[1..9].collect { |ones| "#{tens} #{ones}" } }
-
WORDS = words
-
MULTIPLIERS = [[100, 'hundred'], [1000, 'thousand'], [1000000, 'million'], [1000000000, 'billion']]
-
-
def in_words
-
if self < 100
-
WORDS[self]
-
else
-
value, text = MULTIPLIERS.reverse.detect { |value, text| self >= value }
-
multiplied_value, remainder = self / value, self % value
-
"#{multiplied_value.in_words} #{text}#{(remainder > 0) ? ' ' + remainder.in_words : ''}"
-
end
-
end
-
end
-
class Fixnum; include InWords; end
-
class Bignum; include InWords; end
-
-
if $0 == __FILE__
-
require 'test/unit'
-
class InWordsTest < Test::Unit::TestCase
-
def test_zero_to_nine
-
assert_equal 'zero' , 0.in_words
-
assert_equal 'one' , 1.in_words
-
assert_equal 'two' , 2.in_words
-
assert_equal 'three' , 3.in_words
-
assert_equal 'four' , 4.in_words
-
assert_equal 'five' , 5.in_words
-
assert_equal 'six' , 6.in_words
-
assert_equal 'seven' , 7.in_words
-
assert_equal 'eight' , 8.in_words
-
assert_equal 'nine' , 9.in_words
-
end
-
-
def test_ten_to_twelve
-
assert_equal 'ten' , 10.in_words
-
assert_equal 'eleven' , 11.in_words
-
assert_equal 'twelve' , 12.in_words
-
end
-
-
def test_teens
-
assert_equal 'thirteen' , 13.in_words
-
assert_equal 'fourteen' , 14.in_words
-
assert_equal 'fifteen' , 15.in_words
-
assert_equal 'sixteen' , 16.in_words
-
assert_equal 'seventeen', 17.in_words
-
assert_equal 'eighteen' , 18.in_words
-
assert_equal 'nineteen' , 19.in_words
-
end
-
-
def test_some_more
-
assert_equal 'twenty' , 20.in_words
-
assert_equal 'seventy seven', 77.in_words
-
assert_equal 'ninety nine' , 99.in_words
-
end
-
-
def test_hundreds
-
assert_equal 'one hundred' , 100.in_words
-
assert_equal 'three hundred', 300.in_words
-
assert_equal 'seven hundred seventy seven', 777.in_words
-
assert_equal 'eight hundred eighteen', 818.in_words
-
assert_equal 'five hundred twelve', 512.in_words
-
assert_equal 'nine hundred ninety nine', 999.in_words
-
end
-
-
def test_multipliers
-
assert_equal 'one thousand', 1000.in_words
-
assert_equal 'thirty two thousand seven hundred sixty seven', 32767.in_words
-
assert_equal 'ten million one', 10000001.in_words
-
assert_equal 'one billion two hundred thirty four million five hundred sixty seven thousand eight hundred ninety', 1234567890.in_words
-
end
-
end
-
end
-
module Kernel
-
private
-
def this_method_name
-
caller[0] =~ /`([^']*)'/ and $1
-
end
-
end
-
#only required if we use Base64 (see below)
-
require 'digest'
-
class LegacySslMd5
-
def self.encrypt(*tokens)
-
i=tokens
-
# the tokens passed will be an array of objects, what type of object is irrelevant,
-
# just do what you need to do with them and return a single encrypted string.
-
# for example, you will most likely join all of the objects into a single string and then encrypt that string
-
end
-
-
def self.matches?(crypted, *tokens)
-
# return true if the crypted string matches the tokens.
-
# depending on your algorithm you might decrypt the string then compare it to the token, or you might
-
# encrypt the tokens and make sure it matches the crypted string, its up to you
-
#Ruby 1.8 version - faster but I haven't gotten it to work
-
# hash_with_salt = Base64.decode64 crypted
-
hash_with_salt = crypted.unpack('m')[0]
-
salt = hash_with_salt[0..(hash_with_salt.size-16-1)]
-
plain_pwd=tokens[0]
-
d = Digest::MD5.digest salt+plain_pwd
-
hash_with_salt==salt+d
-
end
-
end
-
-
class CatchJsonParseErrors
-
def initialize(app)
-
@app = app
-
end
-
-
def call(env)
-
begin
-
@app.call(env)
-
rescue ActionDispatch::ParamsParser::ParseError => error
-
if env['HTTP_ACCEPT'] =~ /application\/json/ || env['CONTENT_TYPE'] =~ /application\/json/
-
error_output = "There was a problem in the JSON you submitted: #{error}"
-
return [
-
400, { "Content-Type" => "application/json" },
-
[ { status: 400, error: error_output }.to_json ]
-
]
-
else
-
raise error
-
end
-
end
-
end
-
end
-
class Money
-
def ==(other_money)
-
return false unless defined? other_money.cents
-
cents == other_money.cents && bank.same_currency?(currency, other_money.currency)
-
end
-
end
-
-
1
class Object
-
-
# Return true if the object can be converted to a valid integer.
-
1
def valid_int?
-
begin
-
Integer(self)
-
true
-
rescue ArgumentError
-
false
-
end
-
end
-
-
# Return true if the object can be converted to a valid float.
-
1
def valid_float?
-
begin
-
Float(self)
-
true
-
rescue ArgumentError
-
false
-
end
-
end
-
-
# allows attributes to be set with a default value
-
1
def self.attribute(*arg,&block)
-
(name, default) = arg
-
self.send(:define_method, name) {
-
if instance_variables.include? "@#{name}"
-
self.instance_eval "@#{name}"
-
else
-
if block_given?
-
instance_eval &block
-
else
-
default
-
end
-
end
-
}
-
self.send(:define_method, "#{name}="){ |value|
-
self.instance_eval "@#{name} = value"
-
}
-
end
-
end
-
module PaginatedResponder
-
def to_html
-
if get? && resource.is_a?(ActiveRecord::Relation)
-
controller.paginated_scope(resource)
-
end
-
super
-
end
-
end
-
require 'preferences/lib/preferences/preference_definition'
-
-
# Adds support for defining preferences on ActiveRecord models.
-
#
-
# == Saving preferences
-
#
-
# Preferences are not automatically saved when they are set. You must save
-
# the record that the preferences were set on.
-
#
-
# For example,
-
#
-
# class User < ActiveRecord::Base
-
# preference :notifications
-
# end
-
#
-
# u = User.new(:login => 'admin', :prefers_notifications => false)
-
# u.save!
-
#
-
# u = User.find_by_login('admin')
-
# u.attributes = {:prefers_notifications => true}
-
# u.save!
-
#
-
# == Validations
-
#
-
# Since the generated accessors for a preference allow the preference to be
-
# treated just like regular ActiveRecord attributes, they can also be
-
# validated against in the same way. For example,
-
#
-
# class User < ActiveRecord::Base
-
# preference :color, :string
-
#
-
# validates_presence_of :preferred_color
-
# validates_inclusion_of :preferred_color, :in => %w(red green blue)
-
# end
-
#
-
# u = User.new
-
# u.valid? # => false
-
# u.errors.on(:preferred_color) # => "can't be blank"
-
#
-
# u.preferred_color = 'white'
-
# u.valid? # => false
-
# u.errors.on(:preferred_color) # => "is not included in the list"
-
#
-
# u.preferred_color = 'red'
-
# u.valid? # => true
-
module Preferences
-
module MacroMethods
-
# Defines a new preference for all records in the model. By default,
-
# preferences are assumed to have a boolean data type, so all values will
-
# be typecasted to true/false based on ActiveRecord rules.
-
#
-
# Configuration options:
-
# * <tt>:default</tt> - The default value for the preference. Default is nil.
-
# * <tt>:group_defaults</tt> - Defines the default values to use for various
-
# groups. This should map group_name -> defaults. For ActiveRecord groups,
-
# use the class name.
-
#
-
# == Examples
-
#
-
# The example below shows the various ways to define a preference for a
-
# particular model.
-
#
-
# class User < ActiveRecord::Base
-
# preference :notifications, :default => false
-
# preference :color, :string, :default => 'red', :group_defaults => {:car => 'black'}
-
# preference :favorite_number, :integer
-
# preference :data, :any # Allows any data type to be stored
-
# end
-
#
-
# All preferences are also inherited by subclasses.
-
#
-
# == Associations
-
#
-
# After the first preference is defined, the following associations are
-
# created for the model:
-
# * +stored_preferences+ - A collection of all the custom preferences
-
# specified for a record. This will not include default preferences
-
# unless they have been explicitly set.
-
#
-
# == Named scopes
-
#
-
# In addition to the above associations, the following named scopes get
-
# generated for the model:
-
# * +with_preferences+ - Finds all records with a given set of preferences
-
# * +without_preferences+ - Finds all records without a given set of preferences
-
#
-
# In addition to utilizing preferences stored in the database, each of the
-
# above scopes also take into account the defaults that have been defined
-
# for each preference.
-
#
-
# Example:
-
#
-
# User.with_preferences(:notifications => true)
-
# User.with_preferences(:notifications => true, :color => 'blue')
-
#
-
# # Searching with group preferences
-
# car = Car.find(:first)
-
# User.with_preferences(car => {:color => 'blue'})
-
# User.with_preferences(:notifications => true, car => {:color => 'blue'})
-
#
-
# == Generated accessors
-
#
-
# In addition to calling <tt>prefers?</tt> and +preferred+ on a record,
-
# you can also use the shortcut accessor methods that are generated when a
-
# preference is defined. For example,
-
#
-
# class User < ActiveRecord::Base
-
# preference :notifications
-
# end
-
#
-
# ...generates the following methods:
-
# * <tt>prefers_notifications?</tt> - Whether a value has been specified, i.e. <tt>record.prefers?(:notifications)</tt>
-
# * <tt>prefers_notifications</tt> - The actual value stored, i.e. <tt>record.prefers(:notifications)</tt>
-
# * <tt>prefers_notifications=(value)</tt> - Sets a new value, i.e. <tt>record.write_preference(:notifications, value)</tt>
-
# * <tt>prefers_notifications_changed?</tt> - Whether the preference has unsaved changes
-
# * <tt>prefers_notifications_was</tt> - The last saved value for the preference
-
# * <tt>prefers_notifications_change</tt> - A list of [original_value, new_value] if the preference has changed
-
# * <tt>prefers_notifications_will_change!</tt> - Forces the preference to get updated
-
# * <tt>reset_prefers_notifications!</tt> - Reverts any unsaved changes to the preference
-
#
-
# ...and the equivalent +preferred+ methods:
-
# * <tt>preferred_notifications?</tt>
-
# * <tt>preferred_notifications</tt>
-
# * <tt>preferred_notifications=(value)</tt>
-
# * <tt>preferred_notifications_changed?</tt>
-
# * <tt>preferred_notifications_was</tt>
-
# * <tt>preferred_notifications_change</tt>
-
# * <tt>preferred_notifications_will_change!</tt>
-
# * <tt>reset_preferred_notifications!</tt>
-
#
-
# Notice that there are two tenses used depending on the context of the
-
# preference. Conventionally, <tt>prefers_notifications?</tt> is better
-
# for accessing boolean preferences, while +preferred_color+ is better for
-
# accessing non-boolean preferences.
-
#
-
# Example:
-
#
-
# user = User.find(:first)
-
# user.prefers_notifications? # => false
-
# user.prefers_notifications # => false
-
# user.preferred_color? # => true
-
# user.preferred_color # => 'red'
-
# user.preferred_color = 'blue' # => 'blue'
-
#
-
# user.prefers_notifications = true
-
#
-
# car = Car.find(:first)
-
# user.preferred_color = 'red', car # => 'red'
-
# user.preferred_color(car) # => 'red'
-
# user.preferred_color?(car) # => true
-
#
-
# user.save! # => true
-
def preference(name, *args)
-
unless included_modules.include?(InstanceMethods)
-
class_attribute :preference_definitions
-
self.preference_definitions = {}
-
-
has_many :stored_preferences, :as => :owner, :class_name => 'Preference'
-
-
after_save :update_preferences
-
-
# Named scopes
-
scope :with_preferences, lambda {|preferences| build_preference_scope(preferences)}
-
scope :without_preferences, lambda {|preferences| build_preference_scope(preferences, true)}
-
-
extend Preferences::ClassMethods
-
include Preferences::InstanceMethods
-
end
-
-
# Create the definition
-
name = name.to_s
-
definition = PreferenceDefinition.new(name, *args)
-
self.preference_definitions[name] = definition
-
-
# Create short-hand accessor methods, making sure that the name
-
# is method-safe in terms of what characters are allowed
-
name = name.gsub(/[^A-Za-z0-9_-]/, '').underscore
-
-
# Query lookup
-
define_method("preferred_#{name}?") do |*group|
-
preferred?(name, group.first)
-
end
-
alias_method "prefers_#{name}?", "preferred_#{name}?"
-
-
# Reader
-
define_method("preferred_#{name}") do |*group|
-
Rails.cache.fetch("#{cache_key}/preferred_#{name}/group_#{group.map(&:cache_key)}") do
-
preferred(name, group.first)
-
end
-
end
-
alias_method "prefers_#{name}", "preferred_#{name}"
-
-
# Writer
-
define_method("preferred_#{name}=") do |*args|
-
write_preference(*args.flatten.unshift(name))
-
end
-
alias_method "prefers_#{name}=", "preferred_#{name}="
-
-
# Changes
-
define_method("preferred_#{name}_changed?") do |*group|
-
preference_changed?(name, group.first)
-
end
-
alias_method "prefers_#{name}_changed?", "preferred_#{name}_changed?"
-
-
define_method("preferred_#{name}_was") do |*group|
-
preference_was(name, group.first)
-
end
-
alias_method "prefers_#{name}_was", "preferred_#{name}_was"
-
-
define_method("preferred_#{name}_change") do |*group|
-
preference_change(name, group.first)
-
end
-
alias_method "prefers_#{name}_change", "preferred_#{name}_change"
-
-
define_method("preferred_#{name}_will_change!") do |*group|
-
preference_will_change!(name, group.first)
-
end
-
alias_method "prefers_#{name}_will_change!", "preferred_#{name}_will_change!"
-
-
define_method("reset_preferred_#{name}!") do |*group|
-
reset_preference!(name, group.first)
-
end
-
alias_method "reset_prefers_#{name}!", "reset_preferred_#{name}!"
-
-
definition
-
end
-
end
-
-
module ClassMethods #:nodoc:
-
# Generates the scope for looking under records with a specific set of
-
# preferences associated with them.
-
#
-
# Note thate this is a bit more complicated than usual since the preference
-
# definitions aren't in the database for joins, defaults need to be accounted
-
# for, and querying for the the presence of multiple preferences requires
-
# multiple joins.
-
def build_preference_scope(preferences, inverse = false)
-
joins = []
-
statements = []
-
values = []
-
-
# Flatten the preferences for easier processing
-
preferences = preferences.inject({}) do |result, (group, value)|
-
if value.is_a?(Hash)
-
value.each {|preference, value| result[[group, preference]] = value}
-
else
-
result[[nil, group]] = value
-
end
-
result
-
end
-
-
preferences.each do |(group, preference), value|
-
group_id, group_type = Preference.split_group(group)
-
preference = preference.to_s
-
definition = preference_definitions[preference.to_s]
-
value = definition.type_cast(value)
-
is_default = definition.default_value(group_type) == value
-
-
table = "preferences_#{group_id}_#{group_type}_#{preference}"
-
-
# Since each preference is a different record, they need their own
-
# join so that the proper conditions can be set
-
joins << "LEFT JOIN preferences AS #{table} ON #{table}.owner_id = #{table_name}.#{primary_key} AND " + sanitize_sql(
-
"#{table}.owner_type" => base_class.name.to_s,
-
"#{table}.group_id" => group_id,
-
"#{table}.group_type" => group_type,
-
"#{table}.name" => preference
-
)
-
-
if inverse
-
statements << "#{table}.id IS NOT NULL AND #{table}.value " + (value.nil? ? ' IS NOT NULL' : ' != ?') + (!is_default ? " OR #{table}.id IS NULL" : '')
-
else
-
statements << "#{table}.id IS NOT NULL AND #{table}.value " + (value.nil? ? ' IS NULL' : ' = ?') + (is_default ? " OR #{table}.id IS NULL" : '')
-
end
-
values << value unless value.nil?
-
end
-
-
sql = statements.map! {|statement| "(#{statement})"} * ' AND '
-
{:joins => joins, :conditions => values.unshift(sql)}
-
end
-
end
-
-
module InstanceMethods
-
def self.included(base) #:nodoc:
-
base.class_eval do
-
alias_method :prefs, :preferences
-
end
-
end
-
-
# Finds all preferences, including defaults, for the current record. If
-
# looking up custom group preferences, then this will include all default
-
# preferences within that particular group as well.
-
#
-
# == Examples
-
#
-
# A user with no stored values:
-
#
-
# user = User.find(:first)
-
# user.preferences
-
# => {"language"=>"English", "color"=>nil}
-
#
-
# A user with stored values for a particular group:
-
#
-
# user.preferred_color = 'red', :cars
-
# user.preferences(:cars)
-
# => {"language=>"English", "color"=>"red"}
-
def preferences(group = nil)
-
preferences = preferences_group(group)
-
-
unless preferences_group_loaded?(group)
-
group_id, group_type = Preference.split_group(group)
-
find_preferences(:group_id => group_id, :group_type => group_type).each do |preference|
-
preferences[preference.name] = preference.value unless preferences.include?(preference.name)
-
end
-
-
# Add defaults
-
preference_definitions.each do |name, definition|
-
preferences[name] = definition.default_value(group_type) unless preferences.include?(name)
-
end
-
end
-
-
preferences.inject({}) do |typed_preferences, (name, value)|
-
typed_preferences[name] = value.nil? ? value : preference_definitions[name].type_cast(value)
-
typed_preferences
-
end
-
end
-
-
# Queries whether or not a value is present for the given preference.
-
# This is dependent on how the value is type-casted.
-
#
-
# == Examples
-
#
-
# class User < ActiveRecord::Base
-
# preference :color, :string, :default => 'red'
-
# end
-
#
-
# user = User.create
-
# user.preferred(:color) # => "red"
-
# user.preferred?(:color) # => true
-
# user.preferred?(:color, 'cars') # => true
-
# user.preferred?(:color, Car.first) # => true
-
#
-
# user.write_preference(:color, nil)
-
# user.preferred(:color) # => nil
-
# user.preferred?(:color) # => false
-
def preferred?(name, group = nil)
-
name = name.to_s
-
assert_valid_preference(name)
-
-
value = preferred(name, group)
-
preference_definitions[name].query(value)
-
end
-
alias_method :prefers?, :preferred?
-
-
# Gets the actual value stored for the given preference, or the default
-
# value if nothing is present.
-
#
-
# == Examples
-
#
-
# class User < ActiveRecord::Base
-
# preference :color, :string, :default => 'red'
-
# end
-
#
-
# user = User.create
-
# user.preferred(:color) # => "red"
-
# user.preferred(:color, 'cars') # => "red"
-
# user.preferred(:color, Car.first) # => "red"
-
#
-
# user.write_preference(:color, 'blue')
-
# user.preferred(:color) # => "blue"
-
def preferred(name, group = nil)
-
name = name.to_s
-
assert_valid_preference(name)
-
-
if preferences_group(group).include?(name)
-
# Value for this group/name has been written, but not saved yet:
-
# grab from the pending values
-
value = preferences_group(group)[name]
-
else
-
# Grab the first preference; if it doesn't exist, use the default value
-
group_id, group_type = Preference.split_group(group)
-
preference = find_preferences(:name => name, :group_id => group_id, :group_type => group_type).first unless preferences_group_loaded?(group)
-
-
value = preference ? preference.value : preference_definitions[name].default_value(group_type)
-
preferences_group(group)[name] = value
-
end
-
-
definition = preference_definitions[name]
-
value = definition.type_cast(value) unless value.nil?
-
value
-
end
-
alias_method :prefers, :preferred
-
-
# Sets a new value for the given preference. The actual Preference record
-
# is *not* created until this record is saved. In this way, preferences
-
# act *exactly* the same as attributes. They can be written to and
-
# validated against, but won't actually be written to the database until
-
# the record is saved.
-
#
-
# == Examples
-
#
-
# user = User.find(:first)
-
# user.write_preference(:color, 'red') # => "red"
-
# user.save!
-
#
-
# user.write_preference(:color, 'blue', Car.first) # => "blue"
-
# user.save!
-
def write_preference(name, value, group = nil)
-
name = name.to_s
-
assert_valid_preference(name)
-
-
preferences_changed = preferences_changed_group(group)
-
if preferences_changed.include?(name)
-
old = preferences_changed[name]
-
preferences_changed.delete(name) unless preference_value_changed?(name, old, value)
-
else
-
old = clone_preference_value(name, group)
-
preferences_changed[name] = old if preference_value_changed?(name, old, value)
-
end
-
-
value = convert_number_column_value(value) if preference_definitions[name].number?
-
preferences_group(group)[name] = value
-
-
value
-
end
-
-
# Whether any attributes have unsaved changes.
-
#
-
# == Examples
-
#
-
# user = User.find(:first)
-
# user.preferences_changed? # => false
-
# user.write_preference(:color, 'red')
-
# user.preferences_changed? # => true
-
# user.save
-
# user.preferences_changed? # => false
-
#
-
# # Groups
-
# user.preferences_changed?(:car) # => false
-
# user.write_preference(:color, 'red', :car)
-
# user.preferences_changed(:car) # => true
-
def preferences_changed?(group = nil)
-
!preferences_changed_group(group).empty?
-
end
-
-
# A list of the preferences that have unsaved changes.
-
#
-
# == Examples
-
#
-
# user = User.find(:first)
-
# user.preferences_changed # => []
-
# user.write_preference(:color, 'red')
-
# user.preferences_changed # => ["color"]
-
# user.save
-
# user.preferences_changed # => []
-
#
-
# # Groups
-
# user.preferences_changed(:car) # => []
-
# user.write_preference(:color, 'red', :car)
-
# user.preferences_changed(:car) # => ["color"]
-
def preferences_changed(group = nil)
-
preferences_changed_group(group).keys
-
end
-
-
# A map of the preferences that have changed in the current object.
-
#
-
# == Examples
-
#
-
# user = User.find(:first)
-
# user.preferred(:color) # => nil
-
# user.preference_changes # => {}
-
#
-
# user.write_preference(:color, 'red')
-
# user.preference_changes # => {"color" => [nil, "red"]}
-
# user.save
-
# user.preference_changes # => {}
-
#
-
# # Groups
-
# user.preferred(:color, :car) # => nil
-
# user.preference_changes(:car) # => {}
-
# user.write_preference(:color, 'red', :car)
-
# user.preference_changes(:car) # => {"color" => [nil, "red"]}
-
def preference_changes(group = nil)
-
preferences_changed(group).inject({}) do |changes, preference|
-
changes[preference] = preference_change(preference, group)
-
changes
-
end
-
end
-
-
# Reloads the pereferences of this object as well as its attributes
-
def reload(*args) #:nodoc:
-
result = super
-
-
@preferences.clear if @preferences
-
@preferences_changed.clear if @preferences_changed
-
-
result
-
end
-
-
private
-
# Asserts that the given name is a valid preference in this model. If it
-
# is not, then an ArgumentError exception is raised.
-
def assert_valid_preference(name)
-
raise(ArgumentError, "Unknown preference: #{name}") unless preference_definitions.include?(name)
-
end
-
-
# Gets the set of preferences identified by the given group
-
def preferences_group(group)
-
@preferences ||= {}
-
@preferences[group.is_a?(Symbol) ? group.to_s : group] ||= {}
-
end
-
-
# Determines whether the given group of preferences has already been
-
# loaded from the database
-
def preferences_group_loaded?(group)
-
preference_definitions.length == preferences_group(group).length
-
end
-
-
# Generates a clone of the current value stored for the preference with
-
# the given name / group
-
def clone_preference_value(name, group)
-
value = preferred(name, group)
-
value.duplicable? ? value.clone : value
-
rescue TypeError, NoMethodError
-
value
-
end
-
-
# Keeps track of all preferences that have been changed so that they can
-
# be properly updated in the database. Maps group -> preference -> value.
-
def preferences_changed_group(group)
-
@preferences_changed ||= {}
-
@preferences_changed[group.is_a?(Symbol) ? group.to_s : group] ||= {}
-
end
-
-
# Determines whether a preference changed in the given group
-
def preference_changed?(name, group)
-
preferences_changed_group(group).include?(name)
-
end
-
-
# Builds an array of [original_value, new_value] for the given preference.
-
# If the perference did not change, this will return nil.
-
def preference_change(name, group)
-
[preferences_changed_group(group)[name], preferred(name, group)] if preference_changed?(name, group)
-
end
-
-
# Gets the last saved value for the given preference
-
def preference_was(name, group)
-
preference_changed?(name, group) ? preferences_changed_group(group)[name] : preferred(name, group)
-
end
-
-
# Forces the given preference to be saved regardless of whether the value
-
# is actually diferent
-
def preference_will_change!(name, group)
-
preferences_changed_group(group)[name] = clone_preference_value(name, group)
-
end
-
-
# Reverts any unsaved changes to the given preference
-
def reset_preference!(name, group)
-
write_preference(name, preferences_changed_group(group)[name], group) if preference_changed?(name, group)
-
end
-
-
# Determines whether the old value is different from the new value for the
-
# given preference. This will use the typecasted value to determine
-
# equality.
-
def preference_value_changed?(name, old, value)
-
definition = preference_definitions[name]
-
if definition.type == :integer && (old.nil? || old == 0)
-
# For nullable numeric columns, NULL gets stored in database for blank (i.e. '') values.
-
# Hence we don't record it as a change if the value changes from nil to ''.
-
# If an old value of 0 is set to '' we want this to get changed to nil as otherwise it'll
-
# be typecast back to 0 (''.to_i => 0)
-
value = nil if value.blank?
-
else
-
value = definition.type_cast(value)
-
end
-
-
old != value
-
end
-
-
# Updates any preferences that have been changed/added since the record
-
# was last saved
-
def update_preferences
-
if @preferences_changed
-
@preferences_changed.each do |group, preferences|
-
group_id, group_type = Preference.split_group(group)
-
-
preferences.keys.each do |name|
-
# Find an existing preference or build a new one
-
attributes = {:name => name, :group_id => group_id, :group_type => group_type}
-
preference = find_preferences(attributes).first || stored_preferences.build(attributes)
-
preference.value = preferred(name, group)
-
preference.save!
-
end
-
end
-
-
@preferences_changed.clear
-
end
-
end
-
-
# Finds all stored preferences with the given attributes. This will do a
-
# smart lookup by looking at the in-memory collection if it was eager-
-
# loaded.
-
def find_preferences(attributes)
-
if stored_preferences.loaded?
-
stored_preferences.select do |preference|
-
attributes.all? {|attribute, value| preference[attribute] == value}
-
end
-
else
-
stored_preferences.where(attributes).all
-
end
-
end
-
end
-
end
-
-
ActiveRecord::Base.class_eval do
-
extend Preferences::MacroMethods
-
end
-
# Represents a preferred value for a particular preference on a model.
-
#
-
# == Grouped preferences
-
#
-
# In addition to simple named preferences, preferences can also be grouped by
-
# a particular value, be it a string or ActiveRecord object. For example, a
-
# User may have a preferred color for a particular Car. In this case, the
-
# +owner+ is the User record, the +name+ is "color", and the +group+ is the
-
# Car record. This allows preferences to have a sort of context around them.
-
1
class Preference < ActiveRecord::Base
-
1
belongs_to :owner, :polymorphic => true
-
1
belongs_to :group, :polymorphic => true
-
-
1
validates_presence_of :name, :owner_id, :owner_type
-
1
validates_presence_of :group_type, :if => :group_id?
-
-
1
class << self
-
# Splits the given group into its corresponding id and type. For simple
-
# primitives, the id will be nil. For complex types, specifically
-
# ActiveRecord objects, the id is the unique identifier stored in the
-
# database for the record.
-
#
-
# For example,
-
#
-
# Preference.split_group('google') # => [nil, "google"]
-
# Preference.split_group(1) # => [nil, 1]
-
# Preference.split_group(User.find(1)) # => [1, "User"]
-
1
def split_group(group = nil)
-
1028
if group.is_a?(ActiveRecord::Base)
-
1020
group_id, group_type = group.id, group.class.base_class.name.to_s
-
else
-
8
group_id, group_type = nil, group.is_a?(Symbol) ? group.to_s : group
-
end
-
-
1028
[group_id, group_type]
-
end
-
end
-
-
# The definition of the preference as defined in the owner's model
-
1
def definition
-
# Optimize number of queries to the database by only looking up the actual
-
# owner record for STI cases when the definition can't be found in the
-
# stored owner type class
-
990
owner_type && (find_definition(owner_type.constantize) || find_definition(owner.class))
-
end
-
-
# Typecasts the value depending on the preference definition's declared type
-
1
def value
-
495
value = read_attribute(:value)
-
495
value = definition.type_cast(value) if definition
-
495
value
-
end
-
-
# Only searches for the group record if the group id is specified
-
1
def group_with_optional_lookup
-
group_id ? group_without_optional_lookup : group_type
-
end
-
1
alias_method_chain :group, :optional_lookup
-
-
1
private
-
# Finds the definition for this preference in the given owner class.
-
1
def find_definition(owner_class)
-
990
owner_class.respond_to?(:preference_definitions) && owner_class.preference_definitions[name]
-
end
-
end
-
module Preferences
-
# Represents the definition of a preference for a particular model
-
class PreferenceDefinition
-
# The data type for the content stored in this preference type
-
attr_reader :type
-
-
def initialize(name, *args) #:nodoc:
-
options = args.extract_options!
-
options.assert_valid_keys(:default, :group_defaults)
-
-
@type = args.first ? args.first.to_sym : :boolean
-
-
# Create a column that will be responsible for typecasting
-
@column = ActiveRecord::ConnectionAdapters::Column.new(name.to_s, options[:default], @type == :any ? nil : @type.to_s)
-
-
@group_defaults = (options[:group_defaults] || {}).inject({}) do |defaults, (group, default)|
-
defaults[group.is_a?(Symbol) ? group.to_s : group] = type_cast(default)
-
defaults
-
end
-
end
-
-
# The name of the preference
-
def name
-
@column.name
-
end
-
-
# The default value to use for the preference in case none have been
-
# previously defined
-
def default_value(group = nil)
-
@group_defaults.include?(group) ? @group_defaults[group] : @column.default
-
end
-
-
# Determines whether column backing this preference stores numberic values
-
def number?
-
%w(integer float decimal).include? @column.cast_type
-
# @column.number?
-
end
-
-
# Typecasts the value based on the type of preference that was defined.
-
# This uses ActiveRecord's typecast functionality so the same rules for
-
# typecasting a model's columns apply here.
-
def type_cast(value)
-
@type == :any ? value : ActiveRecord::Type.const_get(@type.to_s.camelize).new.send(:type_cast_from_user, value)
-
end
-
-
# Typecasts the value to true/false depending on the type of preference
-
def query(value)
-
if !(value = type_cast(value))
-
false
-
elsif number?
-
!value.zero?
-
else
-
!value.blank?
-
end
-
end
-
end
-
end
-
module PriceView
-
-
# use this function to update prices via ResellerTier#update_prices
-
def prices_matrix(indexed=true)
-
if indexed
-
prices={}
-
product_variant_items.includes{product_variant_group}.map do |pvi|
-
prices.merge!(pvi.id=>[pvi.product_variant_group.variantable(Certificate).title,
-
pvi.product_variant_group.title, pvi.title, pvi.amount])
-
end
-
else
-
prices=[]
-
product_variant_items.includes{product_variant_group}.map do |pvi|
-
prices<<{variantable_title: pvi.product_variant_group.variantable(Certificate).title,
-
pvg_title: pvi.product_variant_group.title, pvi_title: pvi.title, pvi_amount: pvi.amount}
-
end
-
end
-
prices
-
end
-
-
def pvi_prices_hash
-
prices={}
-
product_variant_items.includes{product_variant_group}.map do |pvi|
-
prices.merge!(pvi.id => pvi.amount)
-
end
-
prices
-
end
-
-
# to update prices call ResellerTier#prices_matrix and then load that hash as `options` parameter
-
# see sample tier creating at the bottom of file
-
def update_prices(options)
-
options.each {|k,v|
-
if k.is_a?(Hash)
-
product_variant_items.where{(title==k[:pvi_title]) &
-
(product_variant_groups.title==k[:pvg_title])}.find{|pvi|
-
pvi.product_variant_group.variantable(Certificate).title==k[:variantable_title]}.
-
update_column :amount, k[:pvi_amount]
-
else
-
if options[:index]
-
product_variant_items.find(k).update_column :amount, v.last
-
else
-
product_variant_items.where{(title==v[2]) &
-
(product_variant_groups.title==v[1])}.find{|pvi|
-
pvi.product_variant_group.variantable(Certificate).title==v[0]}.
-
update_column :amount, v[3]
-
end
-
end
-
}
-
end
-
end
-
-
-
Range.class_eval do
-
def to_friendly
-
to_s.gsub "..", "-"
-
end
-
end
-
module RefParam
-
extend ActiveSupport::Concern
-
-
included do
-
before_create :assign_ref
-
end
-
-
# be sure `ref` attribute exists
-
def assign_ref
-
self.ref="#{initials}-#{SecureRandom.hex(6)}"
-
end
-
-
def initials
-
self.class.to_s.tableize.split("_").map{|w|w[0]}.join
-
end
-
-
def to_param
-
ref
-
end
-
end
-
-
-
1
class String
-
# Return an alternate string if blank.
-
1
def or_else(alternate)
-
blank? ? alternate : self
-
end
-
-
# Capitalize each word (space separated).
-
1
def capitalize_each
-
space = " "
-
split(space).each{ |word| word.capitalize! }.join(space)
-
end
-
-
# Capitalize each word in place.
-
1
def capitalize_each!
-
replace capitalize_each
-
end
-
-
1
def shorten (count = 10, word_boundary = true)
-
if word_boundary
-
if self.length >= count
-
shortened = self[0, count]
-
splitted = shortened.split(/\s/)
-
words = splitted.length
-
splitted[0, words-1].join(" ") + ' ...'
-
else
-
self
-
end
-
else
-
if length >= count
-
self[0, count-4] << ' ...'
-
else
-
self
-
end
-
end
-
end
-
-
1
def self.true?(obj)
-
obj.to_s == "true"
-
end
-
-
1
def true?
-
String.true?(self)
-
end
-
-
1
def urlencode
-
gsub( /[^a-zA-Z0-9\-_\.!~*'()]/n ) {|x| sprintf('%%%02x', x[0]) }
-
end
-
-
end
-
module SubdomainFu
-
-
def self.host_without_subdomain(host)
-
host = "ssl.com" if host=="ssl"
-
parts = host.split('.')
-
#Rails.logger.info "host = #{host}" if parts[-(SubdomainFu.config.tld_size+1)..-1].blank?
-
parts[-(SubdomainFu.config.tld_size+1)..-1].join(".")
-
end
-
-
end
-
1
module V2MigrationProgressAddon
-
1
def self.included(base)
-
4
base.extend(ClassMethods)
-
end
-
-
1
module ClassMethods
-
1
define_method :v2_migration_progresses do
-
V2MigrationProgress.where(:migratable_type =~ base_class.to_s)
-
end
-
-
1
define_method :v2_migration_sources do
-
vmp=v2_migration_progresses
-
table_names = vmp.map(&:source_table_name).uniq
-
s=[]
-
table_names.each do |t|
-
ids=vmp.where{source_table_name =~ t}.map(&:source_id)
-
o=OldSite::Base.descendants.find{|c|
-
c.table_name==t}
-
s+=o.where{o.primary_key.to_sym >> ids}
-
end
-
s
-
end
-
end
-
-
1
def v2_migration_progresses
-
V2MigrationProgress.find_by_migratable(self, :all)
-
end
-
-
1
def v2_migration_sources
-
vmp=v2_migration_progresses
-
vmp.map(&:source_obj) unless vmp.blank?
-
end
-
end